LaVOZs

The World’s Largest Online Community for Developers

'; pandas - How can I automate the ordering of a Stacked Bar plot in Python using Matplotlib? - LavOzs.Com

I am currently creating a stacked bar plot using a dataframe and I'd like to change the ordering of the bars in order of magnitude. I have a dataframe as following:

df = ( 
   H  C  O
A  2  1  3
B  1  2  1
C  3  1  1
D  1  2  3
E  1  3  1)

df.plot.bar(stacked = True).legend(loc='upper center', ncol=3)

The problem I am coming into is that the first column has priority in ordering. I would like an output that stacks bars in increasing value found in each column.

I am not opposed to sending each row into a new list, or dataframe, or indices and plotting them separately and then concatanting, but I am very new to Python.

Do you mean something like this:

fig, ax = plt.subplots()

colors = pd.Series({
    'H':'C0',
    'C':'C1',
    'O':'C2'
})

for i,r in df.iterrows():
    row = r.sort_values().cumsum()[::-1]
    ax.bar([i]*len(row), row, color=row.index.map(colors))

Output:

enter image description here

Related
How do I merge two dictionaries in a single expression in Python?
How can I safely create a nested directory?
How do you change the size of figures drawn with matplotlib?
How to get the current time in Python
How can I add new keys to a dictionary?
How do I concatenate two lists in Python?
Save plot to image file instead of displaying it using Matplotlib
“Large data” work flows using pandas
How to make IPython notebook matplotlib plot inline