Image for post
Image for post

How to Make a Line Plot with Pandas and Matplotlib in a Jupyter Notebook

How to Create a Simple Line Plot, add Axis Labels and Title, Customize Axis Ticks, add a Second Line Plot, and add a Legend

Image for post
Image for post

Step 1: Getting Set Up

import pandas as pd
import requests
import matplotlib.pyplot as plt
Image for post
Image for post

Step 2: Grab some data and create a Dataframe

url = 'https://api.covid19api.com/all'
r = requests.get(url)
json = r.json()
df = pd.Dataframe(json)
Image for post
Image for post

Step 3: Filter Dataframe using .loc

df.shape
Image for post
Image for post
af = df.loc[df.CountryCode == 'AF']
af.shape
Image for post
Image for post

Step 4: Plot Line

fig = plt.figure()
ax = fig.add_subplot()
ax.plot(af.Date, af.Confirmed)
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(af.Date, af.Confirmed)
Image for post
Image for post

Step 5: Change Figure Size

fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot()
ax.plot(af.Date, af.Confirmed)
Image for post
Image for post

Step 6: Customize Ticks with set_major_locator

fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot()
ax.plot(af.Date, af.Confirmed)
ax.xaxis.set_major_locator(plt.MaxNLocator(7))
Image for post
Image for post

Step 7: Add Axis Labels and a Title

Image for post
Image for post
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot()
ax.plot(af.Date, af.Confirmed)
ax.xaxis.set_major_locator(plt.MaxNLocator(7))
ax.set_xlabel("Date")
ax.set_ylabel("Confirmed cases")
ax.set_title("COVID19 Confirmed Cases, Afghanistan")
Image for post
Image for post
Image for post
Image for post

Step 8: Plot 2nd Line

zw = df.loc[df.CountryCode == 'ZW']
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot()
ax.plot(af.Date, af.Confirmed)
ax.plot(zw.Date, zw.Confirmed)
ax.xaxis.set_major_locator(plt.MaxNLocator(7))
ax.set_xlabel("Date")
ax.set_ylabel("Confirmed cases")
ax.set_title("COVID19 Confirmed Cases, Afghanistan vs. Zimbabwe")
Image for post
Image for post
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot()
ax.plot(af.Date, af.Confirmed, color='black')
ax.plot(zw.Date, zw.Confirmed, color='green')
ax.xaxis.set_major_locator(plt.MaxNLocator(7))
ax.set_xlabel("Date")
ax.set_ylabel("Confirmed cases")
ax.set_title("COVID19 Confirmed Cases, Afghanistan vs. Zimbabwe")
Image for post
Image for post

Step 9: Add Legend Labels

ax.legend(['Afghanistan', 'Zimbabwe'])
Image for post
Image for post
ax.legend(['Afghanistan', 'Zimbabwe'],loc="lower left")
best
upper right
upper left
lower left
lower right
right
center left
center right
lower center
upper center
center
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Written by

Documentation and tutorials on Python, Programming, and Data Analysis. FPL Addict. Occasionally writing about biohacking, PMing, and food.

Get the Medium app