如何为Seaborn Histogram的注释匹配hue参数的对应颜色?
让Seaborn直方图注释颜色匹配Hue分组颜色
要实现注释颜色和对应hue分组的直方图颜色一致,你可以通过以下方式修改代码:
- 提取hue分组对应的颜色映射:Seaborn会根据指定的
palette为每个hue类别分配颜色,我们可以从绘图对象中获取这个颜色对应关系。 - 遍历直方图的每个分箱块(patch)时,给每个块匹配对应分组的颜色,用该颜色设置注释文字。
修改后的完整代码如下:
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter 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')) # 获取hue分组对应的颜色数组 hue_colors = ax.collections[0].get_facecolors() # 生成与patch数量匹配的颜色索引:每个分箱有两个patch,循环分配两组颜色 color_indices = [0, 1] * (len(ax.patches) // 2) for p, color_idx in zip(ax.patches, color_indices): # 用对应分组的颜色设置注释 ax.annotate(f'{p.get_height():.0f}\n', (p.get_x() + p.get_width() / 2, p.get_height()), ha='center', va='center', color=hue_colors[color_idx]) plt.show()
关键细节说明:
ax.collections[0].get_facecolors():从绘图的集合对象中提取hue分组的颜色,数组的第一个元素对应第一个hue类别(示例中的'B'),第二个对应第二个类别('R')。color_indices:因为每个分箱包含两个不同hue的块,所以通过重复[0,1]来生成和patch数量匹配的索引列表,确保每个分组的块都能对应到正确的颜色。
内容的提问来源于stack exchange,提问作者artemis
相关产品推荐
相关产品推荐

