python - pandas "stacked"条形图,其中未添加值以给出高度

标签 python pandas matplotlib bar-chart

我正在尝试在 pandas 0.18.1 中显示条形图,其中不同列的值显示在彼此之上但不相加。所以我认为这是一个没有添加所有堆栈值的“stacking”的堆栈条形图。

所以在下面的例子中

import pandas
from pandas import DataFrame

so_example = DataFrame( [(15 , 0 , 0 , 4),(16,  0,  1,  4),(17 , 0 , 0 , 6)]).set_index(0)
so_example.plot.bar(stacked=True)

这给出了Dataframe

>>> so_example
    1  2  3
0          
15  0  0  4
16  0  1  4
17  0  0  6

我得到第二个点“16”的最大高度 1 + 4 = 5 。相反,我希望最大高度为 4,并且像现在一样以绿色显示“1”。

stacked bar plot

如何在不人为减法的情况下实现这一目标。抱歉,我不知道这些“堆叠”图叫什么,所以我的所有搜索都未能产生一个简单的解决方案。

最佳答案

请查看下面的代码,它不是一个完整的解决方案,但基本上可以实现你想要的。

import pandas as pd
import matplotlib.pyplot as plt

so_example = pd.DataFrame( [(15 , 0 , 0 , 4),(16,  0,  1,  4),(17 , 0 , 0 , 6)]).set_index(0)
fig = plt.figure()
ax = fig.add_subplot(111)
_max = so_example.values.max()+1
ax.set_ylim(0, _max)
so_example.ix[:,1].plot(kind='bar', alpha=0.8, ax=ax, color='r')
ax2 = ax.twinx()
ax2.set_ylim(0, _max)
so_example.ix[:,2].plot(kind='bar', alpha=0.8, ax=ax2, color='b')
ax3 = ax.twinx()
ax3.set_ylim(0, _max)
so_example.ix[:,3].plot(kind='bar', alpha=0.8, ax=ax3, color='g')

fig.savefig('c:\haha.png')
fig.show()

enter image description here


这是我的想法:

  1. 首先,我尝试了与您相同的方法,尝试寻找一些即插即用解决方案,但似乎没有
  2. 然后我尝试使用这些值,但您明确表示您不想人为地使用这些值。我个人认为这真的取决于你如何定义 artifical,我的意思是在绘制之前对 Dataframe 进行一些数据处理不会那么困难。
  3. 无论如何,这里我们跳到第三个解决方案,即玩转。因为基本上,您的要求是以堆叠但重叠的方式制作条形图。我的意思是,通常 stacked bar 表示您将所有内容堆叠在一起,没有任何重叠,这就是它被称为 stack 的原因。但是由于您希望以最小值在最前面的方式组织条形,第二小的值在第二个,依此类推...

所以在这里,我使用 twinx() 为每个数据集创建不同的轴层,为了让事情对我来说更容易一些,我没有对它们进行排序,只是使用 alpha=0.8 仅更改透明度。而且我没有在整个过程中使用函数。无论如何,我认为这是一种方法。

关于python - pandas "stacked"条形图,其中未添加值以给出高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38779638/

相关文章:

python - 这可以写成 python reduce 函数吗?

python - 重命名重构期间退格键、删除键和箭头键的行为

python - 是否可以将 matplotlib 注释锚定到 x 轴中的数据坐标,但锚定到 y 轴中的相对位置?

python - 子图中的 Seaborn 热图 - 对齐 x 轴

python - Pandas 数据框 : count number of IDs based on occurence of words in a text column

python - 在 seaborn clustermap 上绘制

python - 如何从 PyTorch 中的数据加载器获取整个数据集

python - 匹配 BeautifulSoup 中的部分 id

python - 按数字或字母符号拆分多列

python - pandas 根据匹配记录的有序列表的 TOP 1 结果连接数据帧