Matplotlib is a library in Python used for plotting charts. It is quite powerful and comes up with a range of charts that can be highly customized. In this tutorial, we’ll look at how to plot a line chart using Matplotlib.
How to plot a line chart in Matplotlib?
Line charts are great to show trends in data by plotting data points connected with a line. In matplotlib, you can plot a line chart using pyplot’s
plot() function. The following is the syntax to plot a line chart:
import matplotlib.pyplot as plt plt.plot(x_values, y_values)
x_values are the values to be plotted on the x-axis and
y_values are the values to be plotted on the y-axis.
Let’s look at some of the examples of plotting a line chart with matplotlib.
1. Plot a line chart with default parameters
We have the data on the number of employees of a company,
A year on year, and want to plot it on a line chart using matplotlib. The data is present in two lists. One list has the employee count while the other has the respective years.
import matplotlib.pyplot as plt # number of employees of A emp_count = [3, 20, 50, 200, 350, 400] year = [2014, 2015, 2016, 2017, 2018, 2019] # plot a line chart plt.plot(year, emp_count) plt.show()
You can see in the above chart that we have the year on the x-axis and the employee count on the y-axis. The chart shows an upward trend in the employee count at the company
A year on year.
2. Customize the formatting of a line chart
The line chart that we got in the previous example is very simple without much formatting. Matplotlib allows a number of different formatting options on your chart. Let’s add axis labels, chart title, and markers for data points on the chart to make it more informative.
import matplotlib.pyplot as plt # number of employees of A emp_count = [3, 20, 50, 200, 350, 400] year = [2014, 2015, 2016, 2017, 2018, 2019] # plot a line chart plt.plot(year, emp_count, 'o-g') # set axis titles plt.xlabel("Year") plt.ylabel("Employees") # set chart title plt.title("Employee Growth at A") plt.show()
In the above above example, you can see that we have Year as the x-axis label, Employees as the y-axis label and Employee Growth at A as the chart title. We have also add circular markers to show each datapoint. Let’s see how we added each.
Format the line properties
In the above example, in addition to the values for the x-axis and y-axis, we provided a third argument,
'o-g'. This argument is the format string. They are “abbreviations for quickly setting basic line properties”.
A format string is made of three parts:
'[marker][line][color]' with each of them being optional. The order can also change (like,
'[line][marker][color]) but its parsing can be ambiguous.
In the format string
o denotes circular marker,
- is for a solid line, and
g is for the color green. If you want a line chart with
* markers and dashed line, use
*-- as your format string.
plt.plot(year, emp_count, '*--')
Refer to the official documentation for a complete list of format string combinations.
Set axis labels and chart title
Matplotlib’s pyplot comes with handy functions to set the axis labels and chart title. You can use pyplot’s
ylabel() functions to set axis labels and use pyplot’s
title() function to set the title for your chart.
3. Plot multiple lines in a single chart
Matplotlib also allows you to plot multiple lines in the same chart. Generally used to show lines that share the same axis, for example, lines sharing the x-axis. The y-axis can also be shared if the second series has the same scale, or if the scales are different you can also plot on two different y-axes. Let’s look at examples for both cases.
Lines with same scale
If both the lines have the same scale you can simply plot the second line on the same plot as per your formatting. For example, let’s show the number of employees of company B along with company A.
import matplotlib.pyplot as plt # number of employees emp_countA = [3, 20, 50, 200, 350, 400] emp_countB = [250, 300, 325, 380, 320, 350] year = [2014, 2015, 2016, 2017, 2018, 2019] # plot two lines plt.plot(year, emp_countA, 'o-g') plt.plot(year, emp_countB, 'o-b') # set axis titles plt.xlabel("Year") plt.ylabel("Employees") # set chart title plt.title("Employee Growth") # legend plt.legend(['A', 'B']) plt.show()
Both lines share the same axes. Also note, that we added a legend to easily distinguish between the two companies.
Lines with different scales
If you want to plot lines sharing the same x-axis but having different scales, you can do so by having different scales for the left and right side of the plot. That is, by having two y-axes. For this, you’ll have to create different axes sharing the same x-axis using the function
import matplotlib.pyplot as plt # number of employees of A emp_countA = [3, 20, 50, 200, 350, 400] revenue = [0.2, 0.5, 0.7, 0.9, 1.8, 2.4] year = [2014, 2015, 2016, 2017, 2018, 2019] # plot employee count on ax1 fig, ax1 = plt.subplots() ax1.plot(year, emp_countA, 'o-g') ax1.set_xlabel("Year") ax1.set_ylabel("Employees") ax1.set_title("Employee and Revenue trend of A") # create ax2 with shared x-axis ax2 = ax1.twinx() # plot revenue on ax2 ax2.plot(year, revenue, '*-b') ax2.set_ylabel("Revenue [$M]") # set the legend fig.legend(['Employees', 'Revenue'], loc='upper left') plt.show()
Here, we plot the employee count and the revenue for
A year-over-year on two different y-axes. You can see that the revenue and employee count do not have the same scale, hence it’s better to plot them on different axes.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having matplotlib version 3.2.2
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Tutorials on matplotlib –
- Change Background Color of Plot in Matplotlib
- Change Font Size of elements in a Matplotlib plot
- Matplotlib – Save Plot as a File
- Change Size of Figures in Matplotlib
- Plot a Bar Chart using Matplotlib
- Plot a Pie Chart with Matplotlib
- Plot Histogram in Python using Matplotlib
- Create a Scatter Plot in Python with Matplotlib
- Plot a Line Chart in Python with Matplotlib
- Save Matplotlib Plot with Transparent Background
- Change Font Type in Matplotlib plots