繁体   English   中英

如何在熊猫中添加堆叠条形图孵化? (...或者如何在 Pandas plot 与 matplotlib 中获取 BarContainer 与 AxisSubplot?)

[英]How to to add stacked bar plot hatching in pandas? (...or how to get BarContainer vs AxisSubplot in pandas plot vs. matplotlib?)

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

关于如何从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)

在此处输入图片说明


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

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

在此处输入图片说明

如何从 pandas.DataFrame.plot() 中获取 BarContainer 对象

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 中的 Rectangles 上设置影线。

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

这样做可以确保您不会抢到不属于酒吧的补丁。


如何让相同的补丁显示在不同项目的相同颜色上

也许在迭代每个条中的补丁时,检查它的facecolor ( patch.get_facecolor ) 并维护一个 {facecolor:hatchsymbol} 字典 - 如果 facecolor 在字典集中否则会得到一个新的阴影符号,添加它和颜色到字典设置舱口。

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 教程值得付出努力。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM