Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

matplotlib - assign a color to a specific box in seaborn.boxplot

I'm calling seaborn.boxplot roughly as follows:

   seaborn.boxplot(ax=ax1,
                    x="centrality", y="score", hue="model", data=data], 
                    palette=seaborn.color_palette("husl", len(models) +1),
                    showfliers=False, 
                    hue_order=order,
                    linewidth=1.5)

Is it possible to make one box stand out by giving it a specific color, while coloring all others with the given color palette?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The boxes made using sns.boxplot are really just matplotlib.patches.PathPatch objects. These are stored in ax.artists as a list.

So, we can select one box in particular by indexing ax.artists. Then, you can set the facecolor, edgecolor and linewidth, among many other properties.

For example (based on one of the examples here):

import seaborn as sns
import matplotlib.pyplot as plt

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
                 data=tips, palette="Set3")

# Select which box you want to change    
mybox = ax.artists[2]

# Change the appearance of that box
mybox.set_facecolor('red')
mybox.set_edgecolor('black')
mybox.set_linewidth(3)

plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...