Matplotlib Line Plot in Python featured image

Matplotlib Line Plot in Python: Plot an Attractive Line Chart

Popular Domains for just 99 Cents at Namecheap!

A line chart is the best way to visualize the relationship between the two sets of values. It tells how one value is dependent upon another value. In this entire tutorial, you will learn how to implement Matplotlib line plot in python.

What is the use of Line Plot?

If you have continuous data values then a line chart is very useful to represent them. A plotting line chart helps you in the identification of some patterns and trends in your data. For example seasonal patterns, large changes over time e.t.c.

Use cases of Line Plot

In real life, there are many examples or use cases of the line plots. Some of them are below.

1 . Finding a correlation between the two stocks.

2. To check whether the current data is continuous or discrete.

3. Prediction of the future trend by analyzing the past trends.

Steps to implement Matplotlib Line Plot in Python

In this section, you will know how to plot a matplotlib line plot in python step by step. Make sure to implement this step by step for more understanding. Please note that I am implementing the Matplotlib line plot in Jupyter Notebook for the sake of simplicity. You can code in your IDEs or notebook as per convenience. But I will suggest you to Jupyter Notebook.

Step 1: Import all the necessary libraries

In this tutorial, I am using NumPy and matplotlib only. So let’s import them.

import numpy as np
import matplotlib.pyplot as plt

Step 2: Style the Chart

Here All the code is executed in the Jupyter notebook. So for visualizing the chart inline you have to call the inline magic command. In the same way, if you want gridlines in the plot then use seaborn style. Add the following lines of code.

%matplotlib inline
plt.style.use('seaborn-whitegrid')

Step 3:  Create a Figure and its axes

After importing and styling the chart the next step is to create a matplotlib figure and its axes. You can do so by the figure() and axes() method. Run the following lines of code.

fig = plt.figure()
ax = plt.axes()

Explanation

In matplotlib figure is an instance of the plt.Figure. You can think of it as a box that contains all objects representing, axes, texts, labels, and graphics. In the same axes is an instance of plt.Axes and is a container that contains ticks and labels that are very helpful in visualizing the content.

When You run the above code you will get a nice gridded figure with axes.

Create a Figure and its axes
Figure and its axes

 

Step 4: Create and Plot Sample Data Points

After the creation of figures and axes. You have to use or create some data points that will be used in plotting. For the demonstration purpose, I am creating sample data points using the NumPy python package.

x = np.linspace(0, 20, 1000)
y = np.cos(x)

Here I am creating two variables x and y. In x I am assigning 10 values using the method np.linspace(). After that, I am passing the cosine of x to the y variable. To find cosine I am using the numpy.cos() method.

Now it’s time to plot the data points on the above-created figure. The plt.plot() method will plot the data points on the figure.

plt.plot(x,y)

Output

Plotting Cosine Wave
Plotting Cosine Wave

You can also plot multiple Matplotlib Line Plots on the same figure. Just use plt.plot() multiple times.  For example, I want to also plot the sin results of the same x data points. Then I will use the following code.

plt.plot(x,np.cos(x));
plt.plot(x,np.sin(x));

Now if you run the code then you will see a line chart one is a cosine in blue color and another is sin chart in orange color.

Output

Plotting Multuple Line Charts on the same figure
Plotting Multiple Line Charts on the same figure

These are the steps to Matplotlib Line Plot in Python. There are also other things you can do or manipulate line charts. Some of the examples are explained in the coming section.

How to change the color of the line in Matplotlib

You can also change the color of the line chart in the figure. To do so you have to pass an extra color argument. Also, there are different ways to assign the color value.

Specify color by name

Here you have to use the name of the color. For example color=”blue”.

plt.plot(x, np.sin(x), color='blue')

Output

Specify color by name

Short Color Code

plt.plot(x, np.sin(x), color='g')

Output

Short Color Code

Grayscale between 0 and 1

plt.plot(x, np.sin(x), color='0.5')

Output

Grayscale between 0 and 1

Using Hex code (RRGGBB from 00 to FF)

plt.plot(x, np.sin(x), color='#FFDD44')

Output

Using Hex code (RRGGBB from 00 to FF)

Using RGB Value

plt.plot(x, np.sin(x), color=(1.0,0.2,0.3))

Output

Using RGB Value

Change the color using all HTML colors

plt.plot(x, np.sin(x), color='chartreuse')

Output

Change the color using all HTML colors

You can see in the above examples there are various ways to change the color of the line chart. It depends upon you to choose the method you want to use. In the next section, you will know how to set line style in matplotlib.

 

Matplotlib Plot Line Style

Sometimes it is very difficult to visualize the chart if there are multiple lines on the same chart. However, you can change the color of each line and it’s good for some number of lines. But the best way is to change the style of the line. In this section, you will know all the ways to plot the line style.

For styling the line you have to pass the linestyle argument.

Solid Line

plt.plot(x, x + 0, linestyle='solid')

Dashed Line

plt.plot(x, x + 10, linestyle='dashed')

Dash with Dot

plt.plot(x, x + 20, linestyle='dashdot')

Dotted Line

plt.plot(x, x + 30, linestyle='dotted')

Output

Matplotlib Plot Line Style using name
Matplotlib Plot Line Style using name

Instead of using the word for changing the style, you can also use the code.

Solid: “-”

Dashed: “–”

DashDot: “-.”

Dotted: “:”

Execute the below lines of code and compare the output with the above method. You will get the same results.

plt.plot(x, x + 0, linestyle='-') # solid
plt.plot(x, x + 10, linestyle='--') # dashed
plt.plot(x, x + 20, linestyle='-.') # dashdot
plt.plot(x, x + 30, linestyle=':'); # dotted

Output

Matplotlib Plot Line Style using code
Matplotlib Plot Line Style using code

If you don’t want to use the color and linestyle parameter and want directly to add style and color. Then you can do so. You have to just pass the color name and style code. Just execute the lines of code.

plt.plot(x, x + 0, '-g') # solid green
plt.plot(x, x + 10, '--c') # dashed cyan
plt.plot(x, x + 20, '-.k') # dashdot black
plt.plot(x, x + 30, ':r'); # dotted red

You will get the output as below.

Output

Matplotlib Plot Line Style using line code and color code
Matplotlib Plot Line Style using line code and color code

How to set axes limits for a plot in Python

Matplotib by default adjust the limits for your figure automatically. But you can also set it manually. To do so you have to pass the range inside the plt. xlim() and plt.ylim(). The plt.xlim() will set the limits on the x-axis and plt.ylim() on the y axis.

plt.plot(x, np.sin(x))
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5)

Output

Setting simple limits on figure
Setting simple limits on figure

You can see in the above figure x limit is set from 0 to 11 and the y  limit is set from -1.5 to 1.5.

You can reverse the limit by reversing the argument.

plt.plot(x, np.sin(x))
plt.xlim(10, 0)
plt.ylim(1.2, -1.2)

Output

Reversing the limits of the figure
Reversing the limits of the figure

The other way to set axes limit is by passing a list containing values like this form, [xmin,xmax,ymin,ymax]. Execute the lines of code and see the output.

plt.plot(x, np.sin(x))
plt.axis([-1, 11, -1.5, 1.])

Output

Setting simple limits on figure using list
Setting simple limits on figure using list

How to Label a Plot in Matplotlib

Now after drawing the line chart, changing the style and color, the final step is to label the plot. Labeling the figure in matplotlib mostly requires three methods. One is plt.title(), the second is plt.xlabel() and the third is plt.ylabel().

Execute the below lines of code.

plt.plot(x, np.sin(x))
plt.title("Sine Curve")
plt.xlabel("x")
plt.ylabel("sin(x)")

Output

Labelling the plot
Labeling the plot

Now you can see how the line chart is looking good. Labeling the chart allows you to read how the data is arranged on the chart. You can also adjust the position, text size, styles e.t.c. You can read more about them in the official Matplotlib Documentation.

Conclusion

The line chart is the best way to describe the relationship between the two continuous data points. Implementing Matplotlib Line Plot not only helps you to properly visualize the chart but also shows some patterns in the figure. It helps you to predict the trend in the future values (Linear Regression).

Hope you have properly understood this tutorial on implementing Matplotlib Line Plot in Python. If you have any queries regarding this then you can contact us for more help. We are always ready to help you.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner