The line plot is the most iconic of all the plots. To draw one in matplotlib, use the
plt.plot() function and pass it a list of numbers used as the y-axis values. Per default, the x-axis values are the list indexes of the passed line. Matplotlib automatically connects the points with a blue line per default. You can change the line type and marker size with additional arguments.
plot([x], y, [fmt], *, data=None, **kwargs)
>>> plot(x, y) # plot x and y using default line style and color >>> plot(x, y, 'bo') # plot x and y using blue circle markers >>> plot(y) # plot y using x as index array 0..N-1 >>> plot(y, 'r+') # ditto, but with red plusses
Minimal Line Plot Examples
The minimal example is the following:
import matplotlib.pyplot as plt plt.plot([0, 1, 2, 3]) plt.ylabel('line plot') plt.show()
The output generated by these four lines of code is the following simple line plot:
So far, so good! Here’s a bit more advanced example using the
seaborn styling for the plot:
import matplotlib.pyplot as plt import numpy as np # I prefer this style to the default plt.style.use('seaborn') # Square numbers from 0-10 inclusive squared = [x**2 for x in range(11)] plt.plot(squared) plt.show()
Easy. In this article, I’ll show you how to add axis labels, plot multiple lines and customize your plot to expertly showcase your data.
Like scatter plots, line plots show the relationship between two variables. Unlike scatter plots, they are often used to measure how a variable changes over time. Thus we would use a line plot to show how the stock market has performed rather than a scatter plot.
Line plots are excellent for time series data because we can put time on the x-axis and whatever we are measuring on the y-axis.
Let’s look at a classic example – the US stock market.
Matplotlib Line Plot Stock Market Example
This plot shows the S&P 500 index over 2019 using matplotlib’s default settings. The S&P 500 tracks the top 500 US stocks and so is a reflection of the stock market overall.
You can download the data for free online.
Note: the dates only include business days because the stock market is only open on business days.
# First 5 business days in 2019 >>> bus2019[:5] [numpy.datetime64('2019-01-01'), numpy.datetime64('2019-01-02'), numpy.datetime64('2019-01-03'), numpy.datetime64('2019-01-04'), numpy.datetime64('2019-01-07')] # First 5 S&P 500 values in 2019 # It contains some missing values (NaN - Not a Number) >>> sp2019[:5] array([[ nan], [2510.03], [2447.89], [2531.94], [2549.69]])
There are gaps in the plot because of the missing values. But the data is good enough for our purposes.
To plot this, we pass
plt.plot() and then call
Great. It shows the S&P 500 values on the y-axis but what are the numbers on the x-axis?
If you only pass a list or NumPy array, matplotlib uses the list indexes for the x-axis values.
>>> len(sp2019) 250
As there are 250 values in sp2019, the x-axis ranges from 0 to 250.
In this case, it would be better if we had dates on the x-axis. To do this, we pass two arguments to
plt.plot(). First the x-axis values, then the y-axis ones.
# x-axis for dates, y-axis for S&P 500 index plt.plot(dates2019, sp2019) plt.show()
Matplotlib spaces the dates out evenly and chooses the best level of accuracy. For this plot, it chose months. It would be annoying if it chose dates down to the day.
Finally, let’s add some axis labels and a title.
plt.plot(bus2019, sp2019) plt.title('S&P500 Index - 2019') plt.xlabel('Date') plt.ylabel('Index') plt.show()
Perfect. To save space, I will exclude the lines of code that set the axis labels and title. But make sure to include them in your plots.
Matplotlib Line Plot Color
Color is an incredibly important part of plotting and deserves an entire article in itself. Check out the Seaborn docs for a great overview.
Color can make or break your plot. Some color schemes make it ridiculously easy to understand the data and others make it impossible.
However, one reason to change the color is purely for aesthetics.
We choose the color of points in
plt.plot() with the keyword
color. The default is blue.
You can set any color you want using an RGB or RGBA tuple (red, green, blue, alpha). Each element of these tuples is a float in
[0.0, 1.0]. You can also pass a hex RGB or RGBA string such as
'#1f1f1f'. However, most of the time you’ll use one of the 50+ built-in named colors. The most common are:
Here’s the plot of the S&P500 index for 2019 using different colors
For each plot, call
sp2019. Then set
c) to your choice
# Blue (the default value) plt.plot(dates2019, sp2019, color='b') # Red plt.plot(dates2019, sp2019, color='r') # Green plt.plot(dates2019, sp2019, c='g') # Black plt.plot(dates2019, sp2019, c='k')
Matplotlib Line Plot Multiple Lines
If you draw multiple line plots at once, matplotlib colors them differently. This makes it easy to recognize the different datasets.
Let’s plot the S&P500 index for 2018 and 2019 on one plot to compare how it performed each month. You do this by making two
plt.plot() calls before calling
plt.plot(sp2019) plt.plot(sp2018) plt.show()
This looks great. It’s very easy to tell the orange and blue lines apart. But there are two problems:
- The date axis doesn’t show dates
- We don’t know which line is for which year.
Matplotlib x axis label
To solve the first problem, we need to rename the numbers on the x-axis. In matplotlib, they are called x-ticks and so we use the
It accepts two arguments:
ticks– a list of positions to place the ticks
labels– a list of labels to describe each tick
In this case, the ticks are
[0, 50, 100, 150, 200, 250] and the labels are the months of the year.
plt.plot(sp2019) plt.plot(sp2018) # Create ticks and labels ticks = [0, 50, 100, 150, 200, 250] labels = ['Jan', 'Mar', 'May', 'Jul', 'Sep', 'Nov'] # Pass to xticks plt.xticks(ticks, labels) plt.show()
Now let’s find out which line is for which year.
Matplotlib Line Plot Legend
To add a legend we use the
plt.legend() function. This is easy to use with line plots.
plt.plot() call, label each line with the
label keyword. When you call
plt.legend(), matplotlib will draw a legend with an entry for each line.
# Add label to 2019 plot plt.plot(sp2019, label='2019') # Add label to 2018 plot plt.plot(sp2018, label='2018') # Call plt.legend to display it plt.legend() plt.xticks(ticks, labels) plt.show()
Perfect. We now have a finished plot. We know what all the axes represent and know which line is which. You can see that 2019 was a better year almost every month.
By default, matplotlib draws the legend in the
'best' location. But you can manually set it using the
loc keyword and one of these 10, self-explanatory, strings:
'upper right', 'upper left', 'upper center'
'lower right', 'lower left', 'lower center'
'center right', 'center left'
'center'(for some reason,
'left'is not an option)
Here are some examples of putting the legend in different locations
Best practice is to place your legend somewhere where it doesn’t obstruct the plot.
There are several linestyles you can choose from. They are set with the
ls keyword in
Their syntax is intuitive and easy to remember. Here are the square numbers with all possible linestyles,
For each plot, call
plt.plot(squared) and set
ls to your choice
# Solid (default) plt.plot(squared, linestyle='-') # Dashed plt.plot(squared, linestyle='--') # Dashdot plt.plot(squared, ls='-.') # Dotted plt.plot(squared, ls=':')
You can also pass the linestyle names instead of the short form string. The following are equivalent:
Matplotlib Line Thickness
You can set the line thickness to any float value by passing it to the
lw keyword in
Here are the square numbers with varying line widths. Smaller numbers mean thinner lines.
plt.plot(squared, linewidth=1) plt.plot(squared, linewidth=3.25) plt.plot(squared, lw=10) plt.plot(squared, lw=15.35)
Matplotlib Line Width
You can set the line width to any float value by passing it to the
lw keyword in
Here are the square numbers with varying line widths
Matplotlib Line Plot with Markers
plt.plot() joins each of the values with a line and doesn’t highlight individual points. You can highlight them with the
There are over 30 built-in markers to choose from. Plus you can use any LaTeX expression and even define your own shapes. We’ll cover the most common ones.
Like most things in matplotlib, the syntax is intuitive. Either, the shape of the string reflects the shape of the marker, or the string is a single letter that matches the first letter of the shape.
'^'– triangle up
'$...$'– LaTeX syntax e.g.
'$\pi$'makes each marker the Greek letter π.
Let’s see some examples
For each plot, call
plt.plot(squared) and set
marker to your choice
# Circle plt.plot(squared, marker='o') # Plus plt.plot(squared, marker='+') # Diamond plt.plot(squared, marker='D') # Triangle Up plt.plot(squared, marker='^')
If you set
linestyle='', you won’t plot a line, just the markers.
# Circle plt.plot(squared, marker='o', linestyle='') # Plus plt.plot(squared, marker='+', linestyle='') # Diamond plt.plot(squared, marker='D', linestyle='') # Triangle Up plt.plot(squared, marker='^', linestyle='')
Matplotlib Line Plot Format Strings
Setting the marker, linestyle and color of a plot is something you want to do all the time. So matplotlib included a quick way to do it
plt.plot(y, fmt) # with x-axis values plt.plot(x, y, fmt)
After passing the y-axis and/or x-axis values, you can pass
fmt. It’s a string made up of three parts:
fmt = '[marker][line][color]'
Each part is optional and you can pass them in any order. You can use the short form markers, linestyles and colors we have discussed in this article. For example,
'o--g' is circle markers, dashed lines and green color.
# These are equivalent plt.plot(x, y, 'o--g') plt.plot(x, y, marker='o', linestyle='--', color='g') plt.plot(x, y, marker='o', ls='--', c='g')
Here are some examples with different markers, linestyles and colors.
# Circles, dash line, red 'o--r' plt.plot(squared, 'o--r') # Plus, dashdot line, green '+-.g' plt.plot(squared, '+-.g') # Diamonds, solid line, black 'D-k' plt.plot(squared, 'D-k') # Triangle up, dot line, blue 'b:^' plt.plot(squared, 'b:^')
If you don’t specify a linestyle in the format string, matplotlib won’t draw a line. This makes your plots look similar to a scatter plot. For this reason, some people prefer to use
plt.scatter(). The choice is up to you.
You now know all the essentials to make professional looking and effective line plots.
You can change the color and plot multiple lines on top of each other. You can write custom labels for the axes and title. You’re able to clearly explain different lines using a legend. And you can customize the look of your plot using color, linewidth, markers and linestyles.
Where To Go From Here
Do you want to earn more money? Are you in a dead-end 9-5 job? Do you dream of breaking free and coding full-time but aren’t sure how to get started?
Becoming a full-time coder is scary. There is so much coding info out there that it’s overwhelming.
Most tutorials teach you Python and tell you to get a full-time job.
That’s ok but why would you want another office job?
Don’t you crave freedom? Don’t you want to travel the world? Don’t you want to spend more time with your friends and family?
There are hardly any tutorials that teach you Python and how to be your own boss. And there are none that teach you how to make six figures a year.
I am a full-time Python freelancer. I work 4 hours per day from anywhere in the world. I set my own schedule and hourly rate. My calendar is booked out months in advance and I have a constant flow of new clients.
Sounds too good to be true, right?
Not at all. I want to show you the exact steps I used to get here. I want to give you a life of freedom. I want you to be a six-figure coder.
Click the link below to watch my pure-value webinar. I’ll show you the exact steps to take you from where you are to a full-time Python freelancer. These are proven, no-BS methods that get you results fast.
It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.
This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer.
Expert Writer & Content Creator – Data Science & Machine Learning.
I help education companies create engaging blog and video content teaching Data Science to beginners. Unlike my competitors, I learn new concepts every day and so understand what it’s like to be a student.
My articles are easy-to-understand, effective and enjoyable to read. My videos are upbeat, engaging and detailed.
To work with me, please reach out on Upwork