How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
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.
matplotlib.pyplot.axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)
- 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:
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.
Now we will plot a graph of the GDP vs year. We have scaled the Y-axis accordingly.
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.
Here is another program where we will highlight the x-axis for a scatter plot.
Example 3 :
Below is another example where we highlight a time range from 2005 to 2010
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course