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.
Advertisement
Answer
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')