Shade region under the curve in matplotlib in Python
We can plot various types of graphical plots in Python with the help of the Matplotlib library. In this text, we are going to learn how to shade the region under the curve in Python using the matplotlib library. If you want to learn how to shade the region under the curve then follow this tutorial.
plt.fill_between()
We will use the plt.fill_between()
method to shade a region under the curve. This method is useful not only in making our plots look nice and professional but also it can give us some useful information depending on how we use it. There are various ways of shading the region under the curve using the plt.fill_between()
method in matplotlib in Python.
Before starting to plot graphs, please make sure your code space or your system satisfies the requirements of the libraries Matplotlib, NumPy, and pandas. NumPy and pandas are libraries that are very useful in manipulating the data of the graphs according to the comfort of the programmer. You may install the libraries using the following commands.
pip install matplotlib pip install numpy pip install pandas
Example 1: Shade region under the curve with filled color in matplotlib
This is an example of an ordinary line graph.
# import the matplotlib library from matplotlib import pyplot as plt # import the numpy library import numpy as np xcoordinate=np.arange(1,31) ycoordinate=x*x plt.title("Normal Line Graph") plt.xlabel('x axis') plt.ylabel('y axis') plt.plot(xcoordinate,ycoordinate) plt.show()
Output:
Now below is the code for the shaded region under the curve using plt.fill_between() method.
#import the matplotlib library from matplotlib import pyplot as plt #import numpy library import numpy as np xcoordinate=np.arange(1,31) ycoordinate=x*x plt.title("Shaded Graph") plt.xlabel('x axis') plt.ylabel('y axis') # This method is used to shade the region under the curve, here alpha lightens shade of the color. plt.fill_between(xcoordinate,ycoordinate,color='blue',alpha=0.5) plt.show()
Output:
Example 2:
import matplotlib.pyplot as plt import numpy as np x=np.array([1,2,3,4,5,6,7,8,9,10]) y=4*x+2 plt.fill_between(x,y,alpha=0.5) plt.show()
Output:
Leave a Reply