是否可以为matplotlib bar plot的左边缘和右边缘设置不同的edgecolor?

lnvxswe2  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(372)

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

pgky5nke

pgky5nke1#

条形图的条形图为 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的例子),您可以研究 containersax . ax.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')

相关问题