I have a dataframe with 3 columns, like this:
JavaScript
x
19
19
1
import pandas as pd
2
3
y = [2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030]
4
n = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
5
w = [80, 65, 88, 65, 60, 70, 60, 55, 65]
6
7
df = pd.DataFrame({'year': y, 'name': n, 'weight': w})
8
9
year name weight
10
0 2005 A 80
11
1 2005 B 65
12
2 2005 C 88
13
3 2015 A 65
14
4 2015 B 60
15
5 2015 C 70
16
6 2030 A 60
17
7 2030 B 55
18
8 2030 C 65
19
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:
JavaScript
1
2
1
df.groupby("name").plot(x="year", y="weight")
2
However, I get multiple plots and that is not what I want. I want all those plots in one figure.
Advertisement
Answer
Does this produce what you’re looking for?
JavaScript
1
10
10
1
import matplotlib.pyplot as plt
2
fig,ax = plt.subplots()
3
4
for name in ['A','B','C']:
5
ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)
6
7
ax.set_xlabel("year")
8
ax.set_ylabel("weight")
9
ax.legend(loc='best')
10