Matplotlib柱形图的左右边缘是否可以设置不同的边框颜色?

3
我想为使用matplotlib.axes.Axes.bar绘制的条形图的不同边缘设置不同的边缘颜色。有人知道如何做到这一点吗?例如:右侧边缘为黑色,但上部、下部和左侧边缘没有边缘/边缘颜色。

谢谢帮助!

1个回答

5
条形图的条柱类型是 matplotlib.patches.Rectangle,只能有一种facecolor和一种edgecolor。如果您想让一侧有另一种颜色,您可以循环生成的条形并在所需边缘上绘制单独的线条。
下面的示例代码实现了右侧以粗黑线条绘制。由于单独的线条无法完美地连接矩形,因此该代码还使用与条形相同的颜色绘制左侧和上侧。
from matplotlib import pyplot as plt
import numpy as np

fig, ax = plt.subplots()
bars = ax.bar(np.arange(10), np.random.randint(2, 50, 10), color='turquoise')
for bar in bars:
    x, y = bar.get_xy()
    w, h = bar.get_width(), bar.get_height()
    ax.plot([x, x], [y, y + h], color=bar.get_facecolor(), lw=4)
    ax.plot([x, x + w], [y + h, y + h], color=bar.get_facecolor(), lw=4)
    ax.plot([x + w, x + w], [y, y + h], color='black', lw=4)
ax.margins(x=0.02)
plt.show()

结果图

提示:如果条形图是用其他方式创建的(例如使用Seaborn),您可以调查axcontainersax.containers是一个containers列表;一个container是一组单独的图形对象,通常是矩形。例如,在堆积条形图中可能会有多个容器。

for container in ax.containers:
    for bar in container:
        if type(bar) == 'matplotlib.patches.Rectangle':
            x, y = bar.get_xy()
            w, h = bar.get_width(), bar.get_height()
            ax.plot([x + w, x + w], [y, y + h], color='black')

谢谢您的回答。解释得非常清楚。但我想知道,如何从bar容器中获取x、y、w、h?我不知道或找不到任何关于get_height、get_width、get_xy()函数的信息,这些函数可以应用于bar容器吗?也许问题在于我使用的是mpl.axes.Axes.bar而不是plt.bar? - Vroni
1
plt.bar()只是为“当前”ax调用mpl.axes.Axes.bar()。我更新了代码以适用于ax(这是建议的方式,当存在多个子图时,plt.bar()可能会让人感到困惑)。我添加了一些说明,以防无法将ax.bar的结果保存到变量中(例如示例中的bars)。 - JohanC
谢谢!这太完美了!我成功地按预期创建了边缘。 - Vroni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接