简体   繁体   中英

Add hue to Seaborn Histogram annotation

I have a snippet of code that produces 2 seaborn.histogram plots on the same axes, split by hue , and annotated:

在此处输入图像描述

The two histograms are appropriately colored differently using the hue parameter, and the count of data in each bin are also appropriately annotated. However, can I also color the annotations / counts of what is in each bin ?

Current MRE :

np.random.seed(8)
t = pd.DataFrame(
    {
    'Value': np.random.uniform(low=100000, high=500000, size=(50,)), 
    'Type': ['B' if x < 6 else 'R' for x in np.random.uniform(low=1, high=10, size=(50,))] 
    }
)

ax = sns.histplot(data=t, x='Value', bins=5, hue='Type', palette="dark")
ax.set(title="R against B")
ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
for p in ax.patches:
    ax.annotate(f'{p.get_height():.0f}\n',
                (p.get_x() + p.get_width() / 2, p.get_height()), ha='center', va='center', color='crimson')        
plt.show()

You're looking for matplotlib.axes.Axes.get_facecolor method .

This way, you can match the color of each annotation with the color of the corresponding histo.

for p in ax.patches:
    color = p.get_facecolor()
    ax.annotate(f"{p.get_height():.0f}\n", (p.get_x() + p.get_width() / 2, p.get_height()),
                ha="center", va="center", color=color, fontweight="bold")

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM