We will have a series of articles dedicated to matplotlib in which we are going to learn about data visualization in python using matplotlib. We start with plotting line graphs in python using matplotlib.
Matplotlib is a python library that allows you to create interactive visualizations, be it static or animated, 2-D, 3-D or polar.
This article is first in the series, in which we are only gonna talk about 2-D line plots. So, let’s get started.
Official site of Matplotlib
To install the matplotlib, Open terminal and type and type
pip install matplotlib
First of all, you need to import the library matplotlib
Code : import matplotlib.pyplot as plt
To make the basic plot, one just needs to specify lists of x and y coordinates.but you can do much more like plotting subplots, giving title to the graphs and axes, changing the color of lines, setting grids, adjusting the length of the axes, etc.
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [5, 6, 7, 8] plt.plot(x,y,'r') # r refers to color of the line # or you can explicitly define coordinates while plotting # as below # plt.plot([1, 2, 3, 4],[5, 6, 7, 8],’r’) plt.title("Our basic line graph") plt.xlabel("x axis") plt.ylabel("y axis") plt.grid(True) plt.show()
Sometimes you need more than one plot in your frame.
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,10,10) plt.plot(x, x**2,'--r', label = "square") plt.plot(x, x**3,'b', label = 'cube') plt.xlim(0,10) plt.ylim(0,1000) plt.legend() plt.show()
→ Sometimes you want to set the limit of your axis, so you can try xlim() and ylim() as shown above which will take two arguments minimum and maximum limit.
→ legend attribute is used to show the labels of corresponding graphs.
You can also plot subplots in a frame
import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0, 10, 1000) #create grid of subplots figure, axes = plt.subplots(2, 2) #create specific subplots axes[0, 0].plot(x1, np.cos(x1)) axes[1, 0].plot(x1, np.sin(x1)) axes[1, 1].plot(x1 , -x1) axes[0, 1].plot(x1 , x1**2) #set tiles of subplots axes[0, 0].set_title("subplot 1") axes[1, 0].set_title("subplot 2") axes[0, 1].set_title("subplot 3") axes[1, 1].set_title("subplot 4") figure.tight_layout()
- There are a lot of other functions and arguments that you can use. so try help function to find out more.
- so use the help function on the functions we used and learn more about them. for example, try help(plt.plot)
- Try different arguments and play with them as you please.beause the key to become a good programmer is exploring things on your own.
- If you have any doubts then feel free to reach us on our Instagram handle
Plotting Line Graphs In Python is really great way to visualize data.
Did you know how to make desktop apps with python? Check Here