Matplotlib – How to create a Line Chart in Python

Spread the love

In this post, you will learn how to create a Line chart in Python Using Matplotlib.

plt.plot() –

Let’s read a dataset to work with

import pandas as pd
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/ICICIBANK.NS.csv"
df = pd.read_csv(url, parse_dates=['Date'])

Create single line chart –

To create a line chart in matplotlib, we use plt.plot() method.

Let’s say you want to plot Date on the x axis and close on the y axis.

import matplotlib.pyplot as plt
%matplotlib inline 

# create a line chart
plt.figure(figsize=(10,8)) 
plt.plot(df['Date'], df['Close'])
plt.xlabel("Year")
plt.ylabel("Closing Price")
plt.savefig('icici_line1.png')
plt.show()

First, we imported the matplotlib library. Then we created a figure with width of 10 inch and a height of 8 inch to draw the line chart. Then we used the plt.plot( x_values, y_values ) to plot the line chart. And we labeled the x axis and y axis and then we saved the figure and used plt.show() to show the figure.

Create Multiple Lines chart –

You can also create multiple lines chart in the same figure.

# create a line chart
plt.figure(figsize=(10,8)) 
plt.plot(df['Date'], df['Open'], label='Open')
plt.plot(df['Date'], df['Close'], label='Close')
plt.legend()
plt.title("Open and close Prices")
plt.xlabel("Year")
plt.ylabel("Price")
plt.savefig('icici_line2.png')
plt.show()

In this figure, we added the open prices. And to distinguish between which line belongs to which, we also added the legend plt.legend() but make sure that you set the label parameter inside the plt.plot() for the legend labels. And we also added a title to the plot using plt.title()

Change line color and style –

If you want, you can also change the line color and style using the color and linestyle parameters.

# change line color and style
plt.figure(figsize=(10,8)) 
plt.plot(df['Date'], df['Open'], color="green", linestyle="--", label='Open')
plt.plot(df['Date'], df['Close'], color="blue", linestyle=":" , label='Close')
plt.legend()
plt.title("Open and close Prices")
plt.xlabel("Year")
plt.ylabel("Price")
plt.savefig('icici_line3.png')
plt.show()

In the color parameter, you can either pass HTML color names or Hex codes. For line style look at the plt.plot() doc.

Zooming into a plot –

Sometime you may want to zoom in and out of a plot. For that you can use the plt.axis(). The axis method takes for arguments.

plt.axis([x_min, x_max, y_min, y_max] )

from datetime import datetime

plt.figure(figsize=(10,8)) 
plt.plot(df['Date'], df['Open'], color="green", linestyle="--", label='Open')
plt.plot(df['Date'], df['Close'], color="blue", linestyle=":" , label='Close')
plt.axis([datetime.strptime('2020-01-01',"%Y-%m-%d"), datetime.strptime('2021-06-30',"%Y-%m-%d"), 250, 800])
plt.legend()
plt.title("Open and close Prices")
plt.xlabel("Year")
plt.ylabel("Price")
plt.savefig('icici_line4.png')
plt.show()

Leave a Reply