You can use the following syntax to plot a time series in pandas:
df.plot(x='date', y='sales')
This particular example creates a time series plot using the column called date for the x-axis and the column called sales for the y-axis.
The following example shows how to use this syntax in practice.
Example: How to Plot a Time Series in Pandas
Suppose we have the following pandas DataFrame that shows the total sales made by some store on various days:
import pandas as pd #create DataFrame df = pd.DataFrame({'date': ['10-1-2023', '10-2-2023', '10-3-2023', '10-4-2023', '10-5-2023', '10-6-2023', '10-7-2023', '10-8-2023'], 'sales': [99, 104, 110, 140, 130, 122, 120, 125]}) #convert date column to datetime format df['date'] = pd.to_datetime(df['date']) #view DataFrame print(df) date sales 0 2023-10-01 99 1 2023-10-02 104 2 2023-10-03 110 3 2023-10-04 140 4 2023-10-05 130 5 2023-10-06 122 6 2023-10-07 120 7 2023-10-08 125
We can use the following syntax to create a time series plot to visualize the total sales by day:
#create time series plot
df.plot(x='date', y='sales')
The x-axis shows the date and the y-axis shows the total sales.
We can also use the following arguments in the plot() function to customize the appearance of the line in the plot:
- linewidth: The width of the line
- color: The color of the line
- linestyle: The style of the line
- legend: Whether or not to display the legend in the plot
We can also use the title(), xlabel() and ylabel() functions from matplotlib to add a title and axis-labels to the plot.
The following code shows how to do so:
import matplotlib.pyplot as plt
#create time series plot with custom line
df.plot(x='date', y='sales'),
linewidth=3, color='purple', linestyle='dashed', legend=False)
#add title and axis labels to plot
plt.title('Sales by Date')
plt.xlabel('Date')
plt.ylabel('Sales')
Notice that the appearance of the line has changed, a title has been added, and axis labels have been added to the plot.
Feel free to play around with the various arguments to make the time series plot appear however you’d like.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
How to Plot Categorical Data in Pandas
How to Plot Value Counts in Pandas
How to Adjust the Figure Size of a Pandas Plot