Python

Matplotlib Line Chart

In this article, we are going to explain how to use the plot function in Python.

The plot is widely used by data analytics to find out the relationship between two numerical datasets. In this article, we are going to see how to use the matplotlib.pyplot to draw a line chart. This article will give you complete details which you need to work on the plot function.

The matplotlib.pypolt offers different ways to plot the graph. To plot the graph as a line chart, we use the function plot ().

The Syntax Is:

1
2
3
import matplotlib.pyplot as plt

plt.plot(x, y)

Here, the x belongs to the x-axis, and the y belongs to the y-axis.

Examples:

Example 1: Draw a Line Chart With Default Parameters

In this example, we are going to draw a line chart using the matplotlib.pyplot default settings. We just create two data points (X and Y) and plot the graph as shown below. This simple example will help you to understand the line graph. The data which we created here explains how the employee counts increase every year from 2011 to 2016. We can see directly from the data, but the same information will be displayed through the line chart.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# line_chart_with_default_settings.py

 

# import the required library

import matplotlib.pyplot as plt

 

# X and Y data

numberofemp = [13, 200, 250, 300, 350, 400]

year = [2011, 2012, 2013, 2014, 2015, 2016]

 

# plot a line chart

plt.plot(year, numberofemp)

plt.show()

Output: python line_chart_with_default_settings.py

Line 3 to 8: We import the required library and create two lists for X and Y. The list numberoftemp represents the X-axis and the list year represents the Y-axis.

Line 11 to 12: We pass those X and Y parameters to the plot function, and then we plot the line graph.

Example 2: Adding the Label Names Along the Axis

In this example, we are going to change some default settings. In the previous example, if we see the graph plot, then it’s difficult to understand what the graph is trying to say because there is no information about x-axis or y-axis data. Also, we are not able to see where the actual data resides in the plot. So, we are going to add markers to see the data points on the plot along with the labels.

The list of the marker which we can use are given below:

marker symbol description
“.” point
“,” pixel
“o” circle
“v” triangle_down
“^” triangle_up
“<“ triangle_left
“>” triangle_right
“1” tri_down
“2” tri_up
“3” tri_left
“4” tri_right
“8” octagon
“s” square
“p” pentagon
“P” plus (filled)
“*” star
“h” hexagon1
“H” hexagon2
“+” plus
“x” x
“X” x (filled)
“D” diamond
“d” thin_diamond
“|” vline
“_” hline
0(TICKLEFT) tickleft
1(TICKRIGHT) tickright
2(TICKUP) tickup
3(TICKDOWN) tickdown
4(CARETLEFT) caretleft
5(CARETRIGHT) caretright
6(CARETUP) caretup
7(CARETDOWN) caretdown
8(CARETLEFTBASE) caretleft (centered at base)
9(CARETRIGHTBASE) caretright (centered at base)
10(CARETUPBASE) caretup (centered at base)
11(CARETDOWNBASE) caretdown (centered at base)
“None”,””or”” nothing
‘$…$’ Render the string using mathtext. E.g., “$f$” for marker showing the letterf.
verts A list of (x, y) pairs used for Path vertices. The center of the marker is located at (0, 0) and the size is normalized, such that the created path is encapsulated inside the unit cell.

Ref: https://matplotlib.org/stable/api/markers_api.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# linechart_labels_marker.py

 

# import the required library

import matplotlib.pyplot as plt

 

# X and Y data

numberofemp = [13, 200, 250, 300, 350, 400]

year = [2011, 2012, 2013, 2014, 2015, 2016]

 

# plot a line chart

plt.plot(year, numberofemp,marker="o")

# set label name of x-axis title

plt.xlabel("Year")

 

# set label name of x-axis title

plt.ylabel("Number of Employees")

 

# set label name of chart title

plt.title("Number of Employee V/s Year Growth")

plt.show()

Output: python linechart_labels_marker.py

Line 11: We add one more parameter in the plot function marker. The marker will be used to display the data points on the graph. There are several markers available to support the data provided.

Line 13 to 19: We set the label names along the x-axis, y-axis along with the title name of the chart.

Example 3:

The plot function has one string formatting concept whose syntax is like this:

1
'[marker][line][color]'

In the above syntax, the first represents the marker value, the second represents the line type, and the last value represents the color. So, we are going to use this string format option in this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# linechart_formattingString.py

 

# import the required library

import matplotlib.pyplot as plt

 

# X and Y data

numberofemp = [13, 200, 250, 300, 350, 400]

year = [2011, 2012, 2013, 2014, 2015, 2016]

 

# plot a line chart

plt.plot(year, numberofemp,"o-r")

# set label name of x-axis title

plt.xlabel("Year")

 

# set label name of x-axis title

plt.ylabel("Number of Employees")

 

# set label name of chart title

plt.title("Number of Employee V/s Year Growth")

plt.show()

Line 11: You can see that we added one string, “o-r”, this string we can divide into three parts in which “o” will represent the maker, “-” will show the line type, and “r” represents the color value red. After using the above string, our plotted line graph will look like as below:

Output: python linechart_formattingString.py

We can also change the string format value according to our choice. So, again we are going to use the string formatting but with different values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# linechart_formattingString.py

 

# import the required library

import matplotlib.pyplot as plt

 

# X and Y data

numberofemp = [13, 200, 250, 300, 350, 400]

year = [2011, 2012, 2013, 2014, 2015, 2016]

 

# plot a line chart

plt.plot(year, numberofemp,"*--b")

# set label name of x-axis title

plt.xlabel("Year")

 

# set label name of x-axis title

plt.ylabel("Number of Employees")

 

# set label name of chart title

plt.title("Number of Employee V/s Year Growth")

plt.show()

Line 11: We change the string format to “*–b”.

After changing the string format, our line graph is displayed below. So, we can adjust the string format value according to our choice. The benefit of using this, we don’t have to use the parameter name as a marker and color. In string format, “b” represents the blue color.

Example 4: Color the Line Plot

In this example, we are going to change the color of the line plot using the parameter. In the previous examples, we have seen this color change option through the string formatting. However, we can also change the color using the parameter like other parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# change_colour.py

 

# import the required library

import matplotlib.pyplot as plt

 

# X and Y data

numberofemp = [13, 200, 250, 300, 350, 400]

year = [2011, 2012, 2013, 2014, 2015, 2016]

 

# plot a line chart

plt.plot(year, numberofemp, marker='D', mfc='green', mec='yellow',ms='7')

 

# set label name of x-axis title

plt.xlabel("Year")

 

# set label name of x-axis title

plt.ylabel("Number of Employees")

 

# set label name of chart title

plt.title("Number of Employee V/s Year Growth")

plt.show()

Line 11: We pass the parameter marker=’D’, mfc (markerfacecolor) green color, mec (markeredgecolor) yellow, and ms (markersize).

The mec (markeredgecolor) is a color that is outside of the data point. The final plot after running the above program will be displayed below:

Example 5: Plot Multiple Charts on the Same Graph When Line Scale Is the Same

The matplotlib also supports drawing multiple charts on the same line graph. We can draw the same graph using the sharing axis. Sometimes you only need to share the x-axis and y-axis. However, sometimes we need to share the x-axis and y-axis, both of which depend on the type of values that we have. Here, in this example, we have both values of the same scale, so we can easily plot the graph on one another.

We are going to see both above scenarios to understand them in a better way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# sharing_x_axis.py

 

# import the required library

import matplotlib.pyplot as plt

 

# X and Y data

numberofemp_A = [13, 200, 250, 300, 350, 400]

numberofemp_B = [10, 100, 150, 200, 250, 800]

year = [2011, 2012, 2013, 2014, 2015, 2016]

 

# plot a line chart

plt.plot(year, numberofemp_A, marker='D', mfc='green', mec='yellow',ms='7')

plt.plot(year, numberofemp_B, marker='o', mfc='red', mec='green',ms='7')

 

# set label name of x-axis title

plt.xlabel("Year")

 

# set label name of x-axis title

plt.ylabel("Number of Employees")

 

# set label name of chart title

plt.title("Number of Employee V/s Year Growth")

 

plt.legend(['numberofemp_A','numberofemp_B'])

plt.show()

Line 7 to 8: We created two data lists, A and B, for the x-axis. But both A and B have the same y-axis values. So in this graph, we are sharing the x-axis only because the scale of the y-axis for both A and B is the same.

Line 12 to 13: We just added one more plot function with some different parameters.

The output is shown below, with the x-axis shared.

Output: python sharing_x_axis.py

Example 6: Multiple Graph When the Scale Is Not the Same

Now, we are going to plot a line graph where we don’t have the x-axis on the same scale. Then, we can plot the different scales of the x-axis on the left and right sides of the graph using the twinx () function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# line_with_different_scale.py

 

# import the required library

import matplotlib.pyplot as plt

 

# X and Y data

numberofemp = [13, 200, 250, 300, 350, 400]

rev = [0.4, 0.6, 0.8, 0.7, 0.8, 0.9]

year = [2011, 2012, 2013, 2014, 2015, 2016]

 

# plot numberofemp on xaxis_1

fig, xaxis_1 = plt.subplots()

xaxis_1.plot(year, numberofemp, marker='D', mfc='green', mec='yellow',ms='7')

xaxis_1.set_xlabel("Year")

xaxis_1.set_ylabel("Number of Employees")

xaxis_1.set_title("Number of Employee and Revenue")

 

# create xaxis_2 with shared x-axis

xaxis_2 = xaxis_1.twinx()

# plot rev on xaxis_2

xaxis_2.plot(year, rev, marker='o', mfc='red', mec='green',ms='7')

xaxis_2.set_ylabel("Rev [$M]")

 

# setting the legend

fig.legend(['Number of Employee', 'Rev'], loc='upper left')

plt.show()

Line 4: We import the required library.

Line 7 to 9: We created three datasets. The new dataset is rev-list, which shows the revenue of the company. Here, we have different x-axis scales. Then, we can show the different scales on the left and right sides. For that, we have to use the twinx () function to create different axes by sharing the same x-axis.

Line 12 to 16:  We used the plt.subplot () function to create our first line chart on the graph.

Line 19 to 22: We shared the x-axis using the twinx() function and assigned the name xaxis_2.

Output: python line_with_different_scale.py

The below output shows the two different x-axes on the left and right sides.

Conclusion:

In this article, we have seen how to use the plot function to draw a line chart. We explained all the major concepts required to draw a line chart using the matplotlib. Also, we added the GitHub link to download the python script for this article.

About the author

Shekhar Pandey