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

2024-03-29 14:48:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为条形图的不同边设置不同的边颜色,使用matplotlib.axes.axes.bar绘制。有人知道怎么做吗?例如:右边缘为黑色,但无边缘/edgecolor用于上、下和左边缘

谢谢你的帮助


Tags: matplotlib颜色绘制bar边缘条形图黑色axes
1条回答
网友
1楼 · 发布于 2024-03-29 14:48:24

条形图的条形图类型为^{},只能有一个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()

resulting plot

PS:如果这些条是以另一种方式创建的(或使用Seaborn的示例),您可以研究containersaxax.containerscontainers的列表;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')

相关问题 更多 >