Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

matplotlib - Pandas plot multiple category lines

Say I have the following data...

date      Score  category                 
2017-01-01   50.0         1
2017-01-01  590.0         2
2017-01-02   30.0         1
2017-01-02  210.4         2
2017-01-03   11.0         1
2017-01-03   50.3         2

So on a daily basis, I have multiple categories, each being assigned a score. Here's my code so far...

vals = [{'date': '2017-01-01', 'category': 1, 'Score': 50},
         {'date': '2017-01-01', 'category': 2, 'Score': 590},
         {'date': '2017-01-02', 'category': 1, 'Score': 30},
         {'date': '2017-01-02', 'category': 2, 'Score': 210.4},
         {'date': '2017-01-03', 'category': 1, 'Score': 11},
         {'date': '2017-01-03', 'category': 2, 'Score': 50.3}]
df = pd.DataFrame(vals)
df.date = pd.to_datetime(df['date'], format='%Y-%m-%d')
df.set_index(['date'],inplace=True)

Which results in a bizarre plot as below. enter image description here

I'd like to have multiple lines, one for each category, and the date on the X-axis - how would I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use groupby and plot

fig, ax = plt.subplots()
for label, grp in df.groupby('category'):
    grp.plot(x = grp.index, y = 'Score',ax = ax, label = label)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...