是否可以为 matplotlib 条形图的左右边缘设置不同的边缘颜色?

Is it possible to set different edgecolors for left and right edge of matplotlib bar plot?

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

感谢帮助!

条形图的条形是 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()

PS:如果条形图是以其他方式创建的(或者使用 Seaborn 的示例),您可以调查 axcontainersax.containerscontainers 的列表; a 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')