Is It Possible To Set Different Edgecolors For Left And Right Edge Of Matplotlib Bar Plot?
Solution 1:
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:
iftype(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')
Post a Comment for "Is It Possible To Set Different Edgecolors For Left And Right Edge Of Matplotlib Bar Plot?"