我有一个以下形式的 DataFarme df。我想绘制一个包含 4 对条形图的图表。这意味着对于四天中的每一天,都有两个代表 0 和 1 的条形。对于这两个条形,我想要一个堆叠的条形。因此每个条形有 3 种颜色,分别代表 <30、30-70 和 >70 。我尝试使用“stacked = True”,但绘制了一个具有 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
最佳答案
您可以使用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()
关于python - 在 pandas 中绘制部分堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45122044/