Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot multiple lines in one figure in Pandas Python based on data from multiple columns? [duplicate]

I have a dataframe with 3 columns, like this:

import pandas as pd

y = [2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030]
n = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
w = [80, 65, 88, 65, 60, 70, 60, 55, 65]

df = pd.DataFrame({'year': y, 'name': n, 'weight': w})

   year name  weight
0  2005    A      80
1  2005    B      65
2  2005    C      88
3  2015    A      65
4  2015    B      60
5  2015    C      70
6  2030    A      60
7  2030    B      55
8  2030    C      65

how can I plot a line for A, B and C, where it shows how their weight develops through the years. So I tried this:

df.groupby("name").plot(x="year", y="weight")

However, I get multiple plots and that is not what I want. I want all those plots in one figure.

enter image description here

like image 313
Jolie Avatar asked Oct 16 '16 13:10

Jolie


2 Answers

Does this produce what you're looking for?

import matplotlib.pyplot as plt
fig,ax = plt.subplots()

for name in ['A','B','C']:
    ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)

ax.set_xlabel("year")
ax.set_ylabel("weight")
ax.legend(loc='best')

enter image description here

like image 158
Angus Williams Avatar answered Oct 17 '22 08:10

Angus Williams


For this specific example a possible solution would be the following

df.set_index("year", inplace=True)
df.groupby("name")["weight"].plot(legend=True, xlabel="Year", ylabel="Weight")

enter image description here

like image 45
H.Alzy Avatar answered Oct 17 '22 09:10

H.Alzy