简体   繁体   English

如何使用 Matplotlib 在 Python 中自动订购堆叠条 plot?

[英]How can I automate the ordering of a Stacked Bar plot in Python using Matplotlib?

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.我目前正在使用 dataframe 创建一个堆叠条 plot ,我想按数量级更改条的顺序。 I have a dataframe as following:我有一个 dataframe 如下:

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.我想要一个 output 以在每列中发现的递增值堆叠条形。

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.我不反对将每一行发送到一个新列表或 dataframe 或索引并分别绘制它们然后连接,但我对 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: Output:

在此处输入图像描述

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

相关问题 使用 matplotlib 的堆积条形图 - stacked bar plot using matplotlib 在python 3中使用matplotlib在堆叠条形图中堆叠多列 - Stacking multiple columns in a stacked bar plot using matplotlib in python 3 如何在 python 中使用 matplotlib 对时间序列数据进行 plot 堆积条形图? - How to plot a stacked bar chart on time series data using matplotlib in python? 使用 matplotlib 的分组百分比堆叠条形图 - Grouped percent stacked bar plot using matplotlib 如何在 Python 中使用 pandas 和 matplotlib 绘制条形图时删除条形之间的空间? - How can I remove space between bars while plotting bar plot using pandas and matplotlib in Python? 如何使用 Plotly-Python plot 水平堆积条 plot? - How to plot a horizontal Stacked bar plot using Plotly-Python? 如何在matplotlib中获取条形图/堆积条形图上的标签? - How to get the label on bar plot/stacked bar plot in matplotlib? python / plotly(快递)中的堆叠条形图 plot:条形图的分组/排序 - Stacked bar plot in python / plotly (express): grouping / ordering of bars 使用MatplotLib python的交互式堆积条形图 - Interactive Stacked Bar Chart using MatplotLib python plot a stacked bar chart using matplotlib keeping the pandas dataframe order as it is using python - plot a stacked bar chart using matplotlib keeping the pandas dataframe order as it is using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM