I am trying to set the edge color for the barplot
created using seaborn
. The issue seems to be when I use hue parameter.
Instead of having a separate color for each individual bar, the edgecolor parameter applies the color to the whole hue/group.
Reproducing the issue via this simple example.
tips = sns.load_dataset("tips")
t_df = tips.groupby(['day','sex'])['tip'].mean().reset_index()
Hence t_df will be ,
clrs = ["#348ABD", "#A60628"]
t_ax = sns.barplot(x='day',y='tip',hue='sex',data=t_df,alpha=0.75,palette= sns.color_palette(clrs),edgecolor=clrs)
plt.setp(t_ax.patches, linewidth=3) # This is just to visualize the issue.
The output this gives ,
What I want is the blue bar should be having blue edge color and same for red. What code change would this require ?
there is no color parameter listed where you might be able to set the colors for your bar graph.
You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.
This is somewhat hacky but it gets the job done:
import matplotlib.patches
# grab everything that is on the axis
children = t_ax.get_children()
# filter for rectangles
for child in children:
if isinstance(child, matplotlib.patches.Rectangle):
# match edgecolors to facecolors
clr = child.get_facecolor()
child.set_edgecolor(clr)
@mwaskom's suggestion is obviously much cleaner. For completeness:
for patch in t_ax.patches:
clr = patch.get_facecolor()
patch.set_edgecolor(clr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With