Matplotlib Line Chart
Line charts work out of the box with matplotlib. You can have multiple lines in a line chart, change color, change type of line, and much more.
Matplotlib is a Python module for plotting. Line charts are one of the many chart types it can create.
Line chart examples
Simple line chart
First import matplotlib and NumPy, these are useful for charting.
You can use the plot(x,y) method to create a line chart.
The NumPy linspace function (sometimes called np.linspace ) is a tool in Python for creating numeric sequences. It’s somewhat similar to the NumPy arrange function, in that it creates sequences of evenly spaced numbers structured as a NumPy array.
numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None)
Returns number spaces evenly w.r.t interval. Similar to arange but instead of step it uses sample number.
start : [optional] start of interval range. By default start = 0
stop: end of interval range
restep: If True, return (samples, step). By default restep = False
num : [int, optional] No. of samples to generate
dtype : type of output array
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1, 1, 50) print(x) y = 2*x + 1 plt.plot(x, y) plt.show()
The plot() method also works for other types of line charts. It doesn’t need to be a straight line, y can have any type of values.
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1, 1, 50) y = 2**x + 1 plt.plot(x, y) plt.show()
Line with Labels
To know what you are looking at, you need metadata. Labels are a type of metadata. They show what the chart is about. The chart has an x label, y label, and title.
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1, 1, 50) y1 = 2*x + 1 y2 = 2**x + 1 plt.figure() plt.plot(x, y1) plt.xlabel("I am x") plt.ylabel("I am y") plt.title("With Labels") plt.show()
More than one line can be in the plot. To add another line, just call the plot(x,y) function again. In the example below, we have two different values for y (y1,y2) that are plotted onto the chart.
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1, 1, 50) y1 = 2*x + 1 y2 = 2**x + 1 plt.figure(num = 3, figsize=(8, 5)) plt.plot(x, y2) plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--' ) plt.show()