简体   繁体   English

在熊猫中绘制部分堆积的条形图

[英]Plot partial stacked bar chart in pandas

I have a DataFarme df in the following form. 我有以下格式的DataFarme df。 I want to plot a graph with 4-pair bars. 我想绘制一个带有4对线的图。 It means for each of the four days, there are two bars representing 0 and 1. For both of the 2 bars, I want to have a stacked bar.So each bar have 3 colors, representing <30, 30-70 and >70. 这意味着对于四天中的每一天,都有两个代表0和1的条。对于这两个条,我都希望有一个堆叠的条。所以每个条都有3种颜色,分别代表<30、30-70和> 70 。 I tried to use the "stacked = True" but a single bar with 6 colors was plotted instead of paired-bars. 我尝试使用“ stacked = True”,但绘制了6种颜色的单个条形图,而不是成对条形图。 Can you anyone please help Thanks a lot. 谁能帮忙,谢谢。

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

You can use bottom parameter. 您可以使用bottom参数。 Here is the way to go 这是要走的路

>> 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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM