绘制pandas

时间:2017-07-15 19:32:18

标签: python pandas

我有以下形式的DataFarme df。我想用4对条形图绘制图形。这意味着对于四天中的每一天,有两个条形代表0和1.对于两个条形,我想要一个堆叠条。所以每个条形有3种颜色,代表<30,30-70和&gt; ; 70。我尝试使用&#34; stacked = True&#34;但是绘制了具有6种颜色的单个条而不是成对条。你能帮助别人吗?非常感谢。

Score          <30       30-70      >70
Gender         0    1    0    1   0     1
2017-07-09    23   10   25   13   12   21
2017-07-10    13   14   12   14   15   10
2017-07-11    24   25   10   15   20   15
2017-07-12    23   17   20   17   18   17

1 个答案:

答案 0 :(得分:3)

您可以使用bottom参数。 这是要走的路

>> import matplotlib.pyplot as plt
>> import numpy as np
>> import pandas as pd
>>
>> columns = pd.MultiIndex.from_tuples([(r, b) for r in ['<30', '30-70', '>70'] 
>>                                             for b in [0, 1]])
>> index = ['2017-07-%s' % d for d in ('09', '10', '11', '12')]
>> df = pd.DataFrame([[23,10,25,13,12,21], [13,14,12,14,15,10],
>>                    [24,25,10,15,20,15], [23,17,20,17,18,17]], 
>>                    columns=columns, index=index)
>>
>> width = 0.25
>> x = np.arange(df.shape[0])
>> xs = [x - width / 2 - 0.01, x + width / 2 + 0.01]
>> for b in [0, 1]:
>>   plt.bar(xs[b], df[('<30', b)], width, color='r')
>>   plt.bar(xs[b], df[('30-70', b)], width, bottom=df[('<30', b)], color='g')
>>   plt.bar(xs[b], df[('>70', b)], width, bottom=df[('<30', b)] + df[('30-70', b)], color='b')
>> plt.xticks(x, df.index)
>> plt.show()

enter image description here