Matplotlib line plots- when and how to use them
Line plots are a nice way to express relationship between two variables. For ex. price v/s quality of a product.
Wikipedia says that a line graph is:
A line chart or line plot or line graph or curve chart is a type of chart which displays information as a series of data points called ‘markers’ connected by straight line segments.
These are also used to express trend in data over intervals of time.
plot(x, y)
x and y are arrays.
Importing necessary libraries
import matplotlib.pyplot as plt
from matplotlib import style
style.use(‘fivethirtyeight’)
Basic plot
x = [1, 2, 3, 4, 5, 6, 7]
y = [8, 4, 6, 4, 9, 4, 2]plt.plot(x, y, 'b') # 'b' specifies blueplt.xlabel("x value") # sets the label for x-axis of the plotplt.ylabel("y value") # set the label for y-axis of the plotplt.title("Plot x y") # sets the title of plotplt.show()
Setting ticks in plot
You can set your tick locations in the x-axis and y-axis using:
plt.xticks(list_ticks)
plt.yticks(list_ticks)
Here, list_ticks is the list of tick locations in the axis.
If we pass an empty list then ticks are removed.
plt.plot(x, y, ‘b’) # ‘b’ specifies blueplt.xlabel(“x value”) # sets the label for x-axis of the plotplt.ylabel(“y value”) # set the label for y-axis of the plotplt.title(“Plot x y”) # sets the title of plotplt.xticks([2, 4, 6]) # sets ticks for x-axisplt.show()
Removing ticks
plt.plot(x, y, 'b') # 'b' specifies blueplt.xlabel("x value") # sets the label for x-axis of the plotplt.ylabel("y value") # set the label for y-axis of the plotplt.title("Plot x y") # sets the title of plotplt.xticks([]) # removes ticks in x-axisplt.yticks([]) # remove ticks in y-axisplt.show()
Adding annotations
An annotation is extra information associated with a particular point in a plot.
plt.text(x-coordinate, y-coordinate, annotation-string)
We can add annotation by specifying coordinates of the data point and a string for annotation text.
plt.plot(x, y, 'b') # 'b' specifies blueplt.xlabel("x value") # sets the label for x-axis of the plotplt.ylabel("y value") # set the label for y-axis of the plotplt.text(5, 9, "Max y") # (5, 9) is the data point to annotateplt.title("Plot x y") # sets the title of plotplt.show()
Markers in plot
Markers in plots are used to show the data points in the plot.
The size and style of the markers can be customized to beautify the plot.
plt.figure(figsize = (9, 7))
plt.plot(x, y, marker = 'o', markersize = 12)
plt.xlabel("x value")
plt.ylabel("y value")
plt.title("Plot with markers")
plt.show()
Other marker styles
“.” for point
“o” for circle
“v” for triangle_down
“^” for triangle_up
Plotting mathematical curves
Line plots are also used to plot mathematical relationships.
In mathematics, we have many functions, if you’re not familiar with them.
You can think of function as a machine which takes an input number and gives another number in output according to some rule.
f(x) = x+3
OR
y = x+3
f(1) = 1+3 = 4
Here, 1 is input and 4 is output.
In python, we plot these functions using numpy arrays for data and numpy functions for mathematical operations.
Plotting x squared
import numpy as np
import matplotlib.pyplot as pltx = np.arange(1, 30, 1) # creating array [1, 2, 3....., 29]y = x*x
plt.figure(figsize= (10, 8))
plt.plot(x, y)
plt.title("y = x\u00b2")
plt.xlabel("x values")
plt.ylabel("y values")
plt.show()
Plotting sine curve
import numpy as np
import matplotlib.pyplot as pltx = np.arange(0, 25, 0.1) # creating array [0, 0.1, 0.2,...., 24.9]y = np.sin(x)
plt.figure(figsize= (12, 8))plt.plot(x, y)plt.title("y = sin(x)")plt.xlabel("x values")
plt.ylabel("y values")plt.show()
Stacked line chart(used for comparison)
Suppose we are having 2 companies and their sales data for a week and we want to compare the performance of these companies.
In this case it seems natural to use two line charts in a single figure.
Legend : This is used to differentiate the two line plots.
Syntax and functions:
plt.plot(x1, y1, label = label_text1) # plot 1
x1 and y1 define the data points
label_text1 is the label for 1st plot
plt.plot(x2, y2, label = label_text2) #plot 2
label_text2 is the label for 2nd plot
plt.legend()
Used to show legend in plot.
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]company1 = [50, 40, 23, 34, 20, 10, 50] # sales of company1
company2 = [30, 40, 30, 45, 20, 45, 30] # sales of company 2plt.figure(figsize = (10, 8))plt.plot(days, company1, label = "Company 1") # line chart company 1plt.plot(days, company2, label = "Company 2") # line chart company 2plt.xlabel("Days")
plt.ylabel("Sales")
plt.legend() # using legend to differentiate the graphs of companiesplt.title("Sales data of company 1 and company 2 for this week")
plt.show()
3D line plot
3D plots are used when a feature is influenced by two variables.
Mathematically, we can say that the function is dependent on two variables.
For ex.
f(x, y) = x+y
OR
z = x+y
For making 3D plots, we need to import a mplot3d toolkit.
After this import, we need to pass projection=”3d” argument to axes function.
from mpl_toolkits import mplot3d
import matplotlib.pyplot as pltplt.figure(figsize = (10, 8))ax = plt.axes(projection=”3d”)plt.title(“3D line plot”)
# Data for a three-dimensional line
xline = [1,2,3,4,5,6,7,8]
yline = [1,2,3,4,5,6,7,8]
zline = [20, 30, 20, 40, 10, 50, 20, 30]ax.plot3D(xline, yline, zline, ‘cyan’)ax.set_xlabel(“x values”)
ax.set_ylabel(“y values”)
ax.set_zlabel(‘z values’)plt.show()
References:
https://en.wikipedia.org/wiki/Line_chart https://en.wikipedia.org/wiki/Annotation https://matplotlib.org/3.1.1/api/markers_api.html https://numpy.org/doc/stable/reference/routines.math.html