python - 如何在 Pandas 中添加堆积条形图孵化? (...或者如何在 Pandas 情节与 matplotlib 中获得 BarContainer 与 AxisSubplot?)

标签 python pandas matplotlib bar-chart stacked

我有一个使用 matplotlib.pyplot.plot() 的代码示例,我想复制它以在堆叠条形图上制作阴影条形段。但是,我一直在使用 pandas.DataFrame.plot() 而不是 matplotlib.pyplot.plot() 制作我的所有其他图形,并希望在这里继续出色地。示例代码返回一个 BarContainer 对象的元组和 pandas.DataFrame.plot() 返回一个 AxisSubplot obect,我不知道如何在两者之间导航。

关于如何从 pandas.DataFrame.plot() 中获取 BarContainer 对象的任何建议,以便我可以使用它们来复制示例?

如果没有,关于如何使用 pandas.DataFrame.plot() 实现我在堆叠条形图上为每个彩色条形段添加阴影线的目标有什么建议吗?

对于我的数据,阴影线将有助于区分相似的颜色,因为我有很多类别和项目,否则结果在视觉上看起来很相似。 (我知道我也可以找到一种方法来绘制更简单的东西,但这样做有助于我进行探索性数据分析。)谢谢!


对堆叠条形图的每个彩色条形段进行孵化的示例工作代码(来自此处:https://matplotlib.org/examples/pylab_examples/hatch_demo.html):

import pandas as pd
import numpy as np  
import matplotlib.pyplot as plt

fig = plt.figure()
ax2 = fig.add_subplot(111)
bars = ax2.bar(range(1, 5), range(1, 5), color='yellow', ecolor='black') + \
    ax2.bar(range(1, 5), [6] * 4, bottom=range(1, 5), color='green', ecolor='black')

patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')
for bar, pattern in zip(bars, patterns):
    bar.set_hatch(pattern)

enter image description here


我希望我的代码(带有简化数据)有每个彩色条形段的影线:

df = pd.DataFrame(np.random.uniform(0,10, size=(5,26)))
df.columns=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ax = df.plot.barh(stacked=True, width=0.98, figsize=(10,5), cmap='gist_ncar')

enter image description here

最佳答案

how to get BarContainer objects out of pandas.DataFrame.plot()

将它们从 Axes' 中过滤掉容器属性

>>> import matplotlib as mpl
>>> ax = df.plot.barh(stacked=True, width=0.98, figsize=(10,5), cmap='gist_ncar')
>>> ax.containers[:4]
[<BarContainer object of 5 artists>, <BarContainer object of 5 artists>, <BarContainer object of 5 artists>, <BarContainer object of 5 artists>]
>>> bars = [thing for thing in ax.containers if isinstance(thing,mpl.container.BarContainer)]

在每个 BarContainer 的矩形上设置影线。

import itertools
patterns = itertools.cycle(('-', '+', 'x', '\\', '*', 'o', 'O', '.'))
for bar in bars:
    for patch in bar:
        patch.set_hatch(next(patterns))
L = ax.legend()    # so hatches will show up in the legend

这样做将确保您不会获取不属于酒吧的 Patch。


how to get the same patches to show up on the same colors across different items

也许在遍历每个条形图 block 时,检查它的 facecolor (patch.get_facecolor) 并维护 {facecolor:hatchsymbol} 的字典 - 如果面色在字典中设置 that hatch 否则获取一个新的 hatch 符号,添加它并设置影线的字典颜色。

d = {}
for bar in bars:
    for patch in bar:
        pat = d.setdefault(patch.get_facecolor(), next(patterns))
        patch.set_hatch(pat)
L = ax.legend()    

Matplotlib Tutorials值得付出努力。

关于python - 如何在 Pandas 中添加堆积条形图孵化? (...或者如何在 Pandas 情节与 matplotlib 中获得 BarContainer 与 AxisSubplot?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59585813/

相关文章:

python - 在没有 Numpy 数组的情况下获取 ValueError

python - 更新 PySDL2 中的窗口位置(帮助!)

python - 任何内置的工作 `range(len(lst))` ?

python - 在 Pandas 中解析 csv 文件时,如何从字符串中删除多余的空格?

python - 纠正时间序列中的时钟漂移

python-3.x - Seaborn 热图更改颜色条的大小

python - isin、str.contains 和 if 条件的区别?

python - 在 Python 中使用 Pandas/matplotlib 更改 X 轴标签

python - 使用双三次插值的彩色 matplotlib map

python - 从 Axes(或Figure)获取 QuadMesh 对象