Plot chart with breakdown in pandas

I have a DataFarme df in the following form. I want to plot a chart with 4 pair bars. This means that for each of the four days, there are two columns representing 0 and 1. For both of the two bars, I want to have a stacked bar. Each bar has 3 colors representing <30, 30-70 and> 70. I tried to use "stacked = True", but instead of paired bars, one panel with 6 colors was built. Can you help someone? Many thanks.

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

      

+3


source to share


1 answer


You can use a parameter bottom

. Here's the way:

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

+2


source







All Articles