【问题标题】:Modifying bar-width and bar-position in matplotlib bar-plot (looping over containers)在 matplotlib 条形图中修改条形宽度和条形位置(循环容器)
【发布时间】:2016-01-08 01:47:39
【问题描述】:

我正在尝试调整以下策略(取自 here)来调整 matplotlib 条形图中条形的大小

# Iterate over bars
for container in ax.containers:
    # Each bar has a Rectangle element as child
    for i,child in enumerate(container.get_children()):
        # Reset the lower left point of each bar so that bar is centered
        child.set_y(child.get_y()- 0.125 + 0.5-hs[i]/2)
        # Attribute height to each Recatangle according to country's size
        plt.setp(child, height=hs[i])

但是在基于两列 DataFrame 的绘图上使用它时遇到了奇怪的行为。代码的相关部分几乎相同:

for container in axes.containers:
        for size, child in zip(sizes, container.get_children()):
            child.set_x(child.get_x()- 0.50 + 0.5-size/2)
            plt.setp(child, width=size)

我得到的效果是条形宽度的大小(我在条形图中使用;不是 hbar)按预期更改,但重新居中仅适用于对应DataFrame的第二列(我已经调换过来检查了),对应下图中较浅的蓝色。

我不太明白这是怎么发生的,因为这两个更改似乎都是作为同一个循环的一部分应用的。我还发现很难排除故障,因为在我的例子中,外循环通过两个容器,而内循环通过与条一样多的子节点(每个容器都是如此)。

我该如何着手解决这个问题?我怎么能找出我实际循环的内容? (我知道每个孩子都是一个矩形对象,但这还不能告诉我两个容器中矩形之间的区别)

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    显然,在修改垂直条形图时,以下方法效果更好:

    for container in axes.containers:
            for i, child in enumerate(container.get_children()):
                child.set_x(df.index[i] - sizes[i]/2)
                plt.setp(child, width=sizes[i])
    

    所以与我采用的原始方法的主要区别在于,我没有获取容器的当前 x_position,而是重新使用 DataFrame 的索引将容器的 x_position 设置为索引减去其一半新宽度。

    【讨论】: