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

Vro*_*oni 3 python matplotlib python-3.7

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

感谢帮助!

Joh*_*anC 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()
Run Code Online (Sandbox Code Playgroud)

结果图

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

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')
Run Code Online (Sandbox Code Playgroud)