Reputation: 7251
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()
Upvotes: 2
Views: 1108
Reputation: 37767
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 :
Upvotes: 3