Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

pandas - seaborn multiple variables group bar plot

I have pandas dataframe, one index(datetime) and three variables(int)

date        A   B       C
2017-09-05  25  261     31
2017-09-06  261 1519    151
2017-09-07  188 1545    144
2017-09-08  200 2110    232
2017-09-09  292 2391    325

I can create grouped bar plot with basic pandas plot.

df.plot(kind='bar', legend=False)

enter image description here

However, I want to display in Seaborn or other libraries to improve my skills.
I found very close answer(Pandas: how to draw a bar plot with two categories and four series each?).
In its suggested answer, it has code that

ax=sns.barplot(x='', y='', hue='', data=data)

If I apply this code to mine, I do not know what my 'y` would be.

ax=sns.barplot(x='date', y=??, hue=??, data=data)

How can I plot multiple variables with Seaborn or other libraries?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think need melt if want use barplot:

data = df.melt('date', var_name='a', value_name='b')
print (data)
          date  a     b
0   2017-09-05  A    25
1   2017-09-06  A   261
2   2017-09-07  A   188
3   2017-09-08  A   200
4   2017-09-09  A   292
5   2017-09-05  B   261
6   2017-09-06  B  1519
7   2017-09-07  B  1545
8   2017-09-08  B  2110
9   2017-09-09  B  2391
10  2017-09-05  C    31
11  2017-09-06  C   151
12  2017-09-07  C   144
13  2017-09-08  C   232
14  2017-09-09  C   325

ax=sns.barplot(x='date', y='b', hue='a', data=data)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)

Pandas solution with DataFrame.plot.bar and set_index:

df.set_index('date').plot.bar()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...