How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?

22 Sep, 2021
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data.
Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time range in time series plot using the pyplot.axvspan() in matplotlib module.
Syntax:
matplotlib.pyplot.axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)
Parameters: 
xmin: Number indicating the starting position of the vertical rectangle on X-axis.
xmin: Number indicating the ending position of the vertical rectangle on X-axis.
ymin: Vertical rectangle starting position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axis
ymax: Vertical rectangle ending position on y axis, it will take values between 0 and 1, 0 being bottom of the axis, 1 being top of the axis.
**kwargs: Other optional parameters to change the properties of the rectangle, like changing color etc.
Below are some examples which depict how to highlight a time range in time series plot:
Example 1:
let us assume that we have a country, and we want to draw a plot of its gross domestic product over a span of many years. Firstly we have to prepare our data so that we can plot a graph. On the Y-axis we will be taking GDP which will be random integers from 5 to 10. On the X-axis we will be taking time period from 1900 to 2020.
We will take GDP of a country and highlight it for a certain period of time.
Python3
# import required modulesimport randomimport matplotlib.pyplot as plt # create datasetyear = [i for i in range(1900,2021)]GDP = []for i in range(121):    GDP.append(random.randint(5,10))     # display dataset   print("Length of year list is: " + str(len(year)))print("Length of GDP list is: " + str(len(GDP)))print("First 10 elements of respective list are: ")print(year[:10])print(GDP[:10])
Output:
Now we will plot a graph of the GDP vs year. We have scaled the Y-axis accordingly.
Python3
# depict time seriesfig, ax = plt.subplots(figsize=(5,5))ymin, ymax = plt. ylim()ax.plot(year,GDP)plt.ylim(ymin * 50, ymax * 50) # adjust labelax.set_ylabel("GDP") # assign titleax.set_title("GDP of country over years" ,size=15)plt.show()
 
 
Output:
 
graph of GDP vs year
 
The subplot keyword returns the figure i.e. the plot and the array of Axes (stored in ax) which we will use to highlight the graph.
 
We will use axvspan() method which adds a vertical span (rectangle) across the axes in a given range, and we can then change the color of the rectangle and then reduce its opacity so that it seems that we have highlighted it.
 
NOTE: Remember to reduce the opacity otherwise it will appear as a solid color rectangle on the graph.The  alpha argument used using **kwargs is used to reduce the opacity.
 
Python3
# depict illustrationfig, ax = plt.subplots(figsize=(5, 5))ymin, ymax = plt. ylim()ax.plot(year, GDP)plt.ylim(ymin * 50, ymax * 50) # adjust labelsax.set_ylabel("GDP") # assign titleax.set_title("GDP of country over years", size=15) # highlight a time rangeax.axvspan(1990, 2010, color="blue", alpha=0.3)plt.show()
highlighted graph of GDP vs year
Example 2:
Here is another program where we will highlight the x-axis for a scatter plot.
Python3
# importing librariesimport matplotlib.pyplot as pltimport random # creating the datasetdate = [i for i in range(2000, 2021)]value = []for i in range(21):    value.append(random.randint(5, 15)) # Create a figure and a set of subplotsfig, ax = plt.subplots(figsize=(10, 6)) # Creating the scatter plotax.scatter(date, value) # Highlighting for a certain period of timeax.axvspan(2002, 2005, alpha=0.3, color="green")plt.show()
highlighting over a  scatter plot
Example 3 : 
Below is another example where we highlight a time range from 2005 to 2010
Python3
# import required modulesimport randomimport matplotlib.pyplot as plt # create datasetx = [int(i) for i in range(2000,2020)]y = [i for i in range(20)] # depict illustrationfig, ax = plt.subplots(figsize=(10, 10))ymin, ymax = plt. ylim()ax.plot(x, y) # highlight a time rangeax.axvspan(2005, 2010, color="green", alpha=0.6)plt.show()
Output:
anikakapoor
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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 | Get unique values from a list
Create a directory in Python