Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edge colors in barplots based on hue/palette

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 ,

enter image description here

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 ,

enter image description here

What I want is the blue bar should be having blue edge color and same for red. What code change would this require ?

like image 804
Spandan Brahmbhatt Avatar asked May 09 '17 21:05

Spandan Brahmbhatt


People also ask

Is it possible to have a separate colors for each category in a bar graph in Matplotlib?

there is no color parameter listed where you might be able to set the colors for your bar graph.

How do you make each bar a different color in python?

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.


1 Answers

This is somewhat hacky but it gets the job done:

enter image description here

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)

EDIT:

@mwaskom's suggestion is obviously much cleaner. For completeness:

for patch in t_ax.patches:
    clr = patch.get_facecolor()
    patch.set_edgecolor(clr)
like image 128
Paul Brodersen Avatar answered Oct 12 '22 14:10

Paul Brodersen