Seaborn:如何为每个组创建一个包含2个变量的条形图?

时间:2017-06-01 00:32:37

标签: python pandas seaborn

我有一个如下的数据框。使用Python看病,我怎样才能创建一个以day_of_week为x轴的条形图,每天有2条显示cr和点击?

df=pd.DataFrame({u'clicks': {0: 19462,
  1: 11474,2: 32522,3: 16031,4: 12828,5: 7856,6: 11395},
 u'cr': {0: 0.0426,1: 0.0595,2: 0.0454,3: 0.0462,4: 0.0408,5: 0.0375,6: 0.0423},
 u'day_of_week': {0: u'Friday',1: u'Monday',2: u'Saturday',3: u'Sunday',
  4: u'Thursday',5: u'Tuesday',6: u'Wednesday'}})

Out[14]: 
   clicks      cr day_of_week
0   19462  0.0426      Friday
1   11474  0.0595      Monday
2   32522  0.0454    Saturday
3   16031  0.0462      Sunday
4   12828  0.0408    Thursday
5    7856  0.0375     Tuesday
6   11395  0.0423   Wednesday

1 个答案:

答案 0 :(得分:3)

您可以将matplotlib与Seaborn样式一起使用:

sns.set()

df=pd.DataFrame({u'clicks': {0: 19462,
  1: 11474,2: 32522,3: 16031,4: 12828,5: 7856,6: 11395},
 u'cr': {0: 0.0426,1: 0.0595,2: 0.0454,3: 0.0462,4: 0.0408,5: 0.0375,6: 0.0423},
 u'day_of_week': {0: u'Friday',1: u'Monday',2: u'Saturday',3: u'Sunday',
  4: u'Thursday',5: u'Tuesday',6: u'Wednesday'}})


df = df.set_index('day_of_week')

fig = plt.figure(figsize=(7,7)) # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as a
width = .3

df.clicks.plot(kind='bar',color='green',ax=ax,width=width, position=0)
df.cr.plot(kind='bar',color='blue', ax=ax2,width = width,position=1)

ax.grid(None, axis=1)
ax2.grid(None)

ax.set_ylabel('clicks')
ax2.set_ylabel('c r')

ax.set_xlim(-1,7)

enter image description here