Mquinn46
Mquinn46

Reputation: 29

Creating a plot with two lines in using Panda (python)

I'm trying to compare two sets of data - CO2 emissions from the UK and Thailand using a publicly available data set. I've used the below code to get separate line graphs however I am struggling to merge the two lines into one plot, can someone please help?

import pandas as pd

import matplotlib.pyplot as plt

download_url = (
"https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.csv"
)

df = pd.read_csv(download_url)
type(df)

pd.set_option("display.max.columns", None)

uk = df[(df["country"] == 'United Kingdom')]
thailand = df[(df["country"] == 'Thailand')]

%matplotlib

uk.plot(x="year", y="co2")

thailand.plot(x="year", y="co2")

Upvotes: 1

Views: 38

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

You can create an axis instance and pass that to plot:

fig, ax = plt.subplots()

uk.plot(x="year", y="co2", ax=ax, label='UK')

thailand.plot(x="year", y="co2", ax=ax, label='Thailand')

You can also use seaborn:

import seaborn as sns

# read data
df = pd.read_csv(download_url)

plot_data = df[df['country'].isin(['United Kingdom', 'Thailand'])

sns.lineplot(x='year', y='co2', hue='country')

Upvotes: 2

Related Questions