Seaborn柱状图深色条形与图例不匹配且数值异常求助
问题排查与解决
1. 数值显示错误(最高值应为36却显示13)
Seaborn的barplot()默认会对y轴数据做聚合计算(默认取均值),如果你的数据在同一x+hue分组下有多个样本,它会自动计算该组的平均值,导致显示的数值不是原始数据的最大值。
解决方式:
- 若要展示每个分组的总和,修改代码,指定
estimator参数为sum:ax = sns.barplot(data=data, x=col_name1, y=col_name2, hue=col_name3, saturation=1, estimator=sum) - 若要展示原始数据的单个条目条形,需确保数据格式为每个条目单独一行,同时可以检查是否存在重复分组导致的自动聚合。
2. 深色条形与图例颜色不匹配
你的代码里matplotlib导入错误,正确导入应为import matplotlib.pyplot as plt,错误的导入会导致Seaborn与Matplotlib的渲染逻辑不兼容,进而引发颜色映射异常。
解决步骤:
- 修正导入语句:
import matplotlib.pyplot as plt import seaborn as sns - 若修正导入后颜色仍不匹配,检查
col_name3对应的类别是否存在格式问题(如字符串前后有空格),导致Seaborn误判为不同类别;也可以手动指定调色板强制颜色匹配:# 自定义调色板,替换为你的类别和对应颜色 custom_palette = {"类别A": "#2c3e50", "类别B": "#e74c3c", "类别C": "#3498db"} ax = sns.barplot(data=data, x=col_name1, y=col_name2, hue=col_name3, saturation=1, palette=custom_palette)
完整修正示例代码
import matplotlib.pyplot as plt import seaborn as sns fig = plt.figure(figsize=(25,15)) # 以展示分组总和为例 ax = sns.barplot(data=data, x=col_name1, y=col_name2, hue=col_name3, saturation=1, estimator=sum) # 可选:给每个条形添加数值标签 for p in ax.patches: height = p.get_height() ax.text(p.get_x() + p.get_width()/2., height, f'{int(height)}', ha='center', va='bottom', fontsize=12) plt.show()
内容的提问来源于stack exchange,提问作者user6688
相关产品推荐
相关产品推荐

