# Matplotlib Line Plot in Python: Plot an Attractive Line Chart 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.

### 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

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

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 ### Short Color Code

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

Output ### Grayscale between 0 and 1

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

Output ### Using Hex code (RRGGBB from 00 to FF)

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

Output ### Using RGB Value

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

Output ### Change the color using all HTML colors

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

Output 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

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

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

## 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

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

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

## 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

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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.7937779,"math_prob":0.92511564,"size":8077,"snap":"2023-40-2023-50","text_gpt3_token_len":1982,"char_repetition_ratio":0.15867707,"word_repetition_ratio":0.034163702,"special_character_ratio":0.24947381,"punctuation_ratio":0.15046677,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99924076,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],"im_url_duplicate_count":[null,2,null,2,null,2,null,2,null,3,null,2,null,3,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-09-29T19:31:45Z\",\"WARC-Record-ID\":\"<urn:uuid:39be2347-938a-46f3-9699-c60a8943f8c9>\",\"Content-Length\":\"238779\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:2b2fb1bb-9351-4f4a-a9e2-0d001cf48fd9>\",\"WARC-Concurrent-To\":\"<urn:uuid:566d8c4b-d1a3-405f-b8cb-b06b5997daaf>\",\"WARC-IP-Address\":\"172.67.210.189\",\"WARC-Target-URI\":\"https://www.datasciencelearner.com/matplotlib-line-plot-in-python/\",\"WARC-Payload-Digest\":\"sha1:6ZR6KEBZBSUIF5Q6VXOES2R2YPO7HZNM\",\"WARC-Block-Digest\":\"sha1:C5LW3EYBT55LNRVRHF6G2657GX3CQLE3\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233510528.86_warc_CC-MAIN-20230929190403-20230929220403-00261.warc.gz\"}"}