问题描述
我想为条形图的不同边设置不同的边颜色,用 matplotlib.axes.Axes.bar 绘制.有谁知道如何做到这一点?例如:右边缘为黑色边缘,但上、下和左边缘没有边缘/边缘颜色.
感谢您的帮助!
条形图的条形类型为
PS:如果条形是以其他方式创建的(或例如使用 Seaborn),您可以调查 ax
的 containers
.ax.containers
是一个 containers
的列表;container
是一组单独的图形对象,通常是矩形.可以有多个容器,例如在堆积条形图中.
用于 ax.containers 中的容器:对于容器中的酒吧:如果 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')
I would like to set different edgecolors for the different edges of a bar plot, plotted with matplotlib.axes.Axes.bar. Does anyone know how to do this? For example: black edges for right edge but no edges/edgecolor for upper, lower and left edges.
Thanks for help!
The bars of a bar plot are of type matplotlib.patches.Rectangle
which can only have one facecolor
and only one edgecolor
. If you want one side to have another color, you can loop through the generated bars and draw a separate line over the desired edge.
The example code below implements the right side draw in a thick black line. As a separate line doesn't join perfectly with the rectangle, the code also draws the left and upper side with the same color as the bar.
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: If the bars were created in another way (or example using Seaborn), you can investigate the containers
of the ax
. ax.containers
is a list of containers
; a container
is a grouping of individual graphic objects, usually rectangles. There can be multiple containers, for example in a stacked bar plot.
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')
这篇关于是否可以为 matplotlib 条形图的左右边缘设置不同的边缘颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!