我想为使用matplotlib.axes.Axes.bar绘制的条形图的不同边缘设置不同的边缘颜色。有人知道如何做到这一点吗?例如:右侧边缘为黑色,但上部、下部和左侧边缘没有边缘/边缘颜色。
谢谢帮助!
谢谢帮助!
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),您可以调查ax
的containers
。 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')
plt.bar()
只是为“当前”ax调用mpl.axes.Axes.bar()
。我更新了代码以适用于ax
(这是建议的方式,当存在多个子图时,plt.bar()
可能会让人感到困惑)。我添加了一些说明,以防无法将ax.bar
的结果保存到变量中(例如示例中的bars
)。 - JohanC