How to Plot a Time Series in Matplotlib? - GeeksforGeeks

27 Jan, 2022
Time series data is the data marked by some time. Each point on the graph represents a measurement of both time and quantity.  A time-series chart is also known as a fever chart when the data are connected in chronological order by a straight line that forms a succession of peaks and troughs. x-axis of the chart is used to represent time intervals. y-line locates values of the parameter getting monitored.
We will use the syntax mentioned below to draw a Time Series graph:
Syntax:
plt.plot(dataframe.X, dataframe.Y)
where
X variable belongs to the datetime. datetime() class in the given dataframe.
Y variable belongs to the values corresponding to date
We can also rotate the axis by using xticks() function
Syntax:
plt.xticks(rotation, ha)
where
rotation describes the degrees you want to rotate
ha describes the position like right, left, top, bottom
We need to have two axes for our graph i.e X and Y-axis. We will start by having a dataframe to plot the graph.
We can either make our own data frame or use some publicly available data frames. In X-axis we should have a variable of DateTime. In Y-axis we can have the variable which we want to analyze with respect to time.
plt.plot()  method is used to plot the graph in matplotlib.
To provide labels and title to make our graph meaningful we can use methods like – plt.title(), plt.xlabel(), plt.ylabel()
Example 1:
Let say we have a dataframe of the days of the week and the number of classes on each day of the upcoming week. We are  Taking 7 days from 1-11-2021 to 7-11-2021
Python3
# import modulesimport pandas as pdimport matplotlib.pyplot as pltimport datetimeimport numpy as np # create dataframe dataframe = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)                                                    for i in range(7)]),                          'classes': [5, 6, 8, 2, 3, 7, 4]}) # Plotting the time series of given dataframeplt.plot(dataframe.date_of_week, dataframe.classes) # Giving title to the chart using plt.titleplt.title('Classes by Date') # rotating the x-axis tick labels at 30degree# towards rightplt.xticks(rotation=30, ha='right') # Providing x and y label to the chartplt.xlabel('Date')plt.ylabel('Classes')
Output:
We can also create scatter plots with the help of Time Series with the help of matplotlib.
Example 2: Scatter time series plot of the given dataframe
Python3
#import modulesimport pandas as pdimport matplotlib.pyplot as pltimport datetimeimport numpy as np # Let say we have a dataframe of the days of# the week and number of classes in each day of the upcoming week.# Taking 7 days from 1-11-2021 to 7-11-2021 dataframe = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)                                                    for i in range(7)]),                          'classes': [5, 6, 8, 2, 3, 7, 4]}) # To draw scatter time series plot of the given dataframeplt.plot_date(dataframe.date_of_week, dataframe.classes) # rotating the x-axis tick labels at 30degree towards rightplt.xticks(rotation=30, ha='right') # Giving title to the chart using plt.titleplt.title('Classes by Date') # Providing x and y label to the chartplt.xlabel('Date')plt.ylabel('Classes')
Output:
Similarly, we can plot the time series of two dataFrames and compare them. Let say we have two colleges -‘XYZ’ and ‘ABC’. Now we need to compare these two by time-series graph of matplotlib. 
Example 3:
Python3
# Initialising required librariesimport pandas as pdimport matplotlib.pyplot as pltimport datetimeimport numpy as np # ABC colllege classes by date- from 01-11-2021 to 07-11-2021abc = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)                                              for i in range(7)]),                    'classes': [5, 6, 8, 2, 3, 7, 4]})  # XYZ colllege classes by date - from 01-11-2021 to 07-11-2021xyz = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)                                              for i in range(7)]),                    'classes': [2, 3, 7, 3, 4, 1, 2]}) # plotting the time series of ABC college dataframeplt.plot(abc.date_of_week, abc.classes) # plotting the time series of XYZ college dataframeplt.plot(xyz.date_of_week, xyz.classes, color='green') # Giving title to the graphplt.title('Classes by Date') # rotating the x-axis tick labels at 30degree# towards rightplt.xticks(rotation=30, ha='right') # Giving x and y label to the graphplt.xlabel('Date')plt.ylabel('Classes')
Output:
Similarly, we can plot the time series plot from a dataset. Here is the link to the dataset
Example 4:
Python3
# Initialising required librariesimport pandas as pdimport matplotlib.pyplot as pltimport datetimeimport numpy as np # Loading the datasetdata = pd.read_csv("C:/Users/aparn/Desktop/data.csv") # X axis is price_dateprice_date = data['Date'] # Y axis is price closingprice_close = data['Close'] # Plotting the timeseries graph of given datasetplt.plot(price_date, price_close) # Giving title to the graphplt.title('Prices by Date') # rotating the x-axis tick labels at 30degree# towards rightplt.xticks(rotation=30, ha='right') # Giving x and y label to the graphplt.xlabel('Price Date')plt.ylabel('Price Close')
Output:
varshagumber28
sumitgumber28
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python