Seaborn绘制Pandas DataFrame柱状图时出现虚假零值的求助
修复Seaborn柱状图中出现的虚假零值问题
在使用Seaborn绘制Pandas DataFrame的柱状图时,第二根与第三根柱子之间出现了无法消除的虚假零值:

问题原因
Temp列存储的是整数类型,Seaborn默认会将这类数值视为连续变量处理。由于10和25之间存在数值间隔,Seaborn会在该间隔处预留刻度位置,最终表现为虚假的零值柱子。
解决方案
将Temp列转换为字符串类型,让Seaborn将其当作分类变量处理,即可消除虚假零值。
修改后的完整代码
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns data = { 'Temp': [5, 10, 25, 50, 100, 5, 10, 25, 50, 100, 5, 10, 25, 50, 100, 5, 10, 25, 50, 100], 'Measurement': ['mean', 'mean', 'mean', 'mean', 'mean', 'std', 'std', 'std', 'std', 'std', 'min', 'min', 'min', 'min', 'min', 'max', 'max', 'max', 'max', 'max'], 'Value': [-0.03, -0.05, -0.07, -0.09, -0.09, 0.24, 0.44, 0.69, 1.11, 1.45, -2.36, -4.56, -5.86, -11.68, -14.68, 1.30, 3.50, 5.26, 9.28, 11.14] } df_melted = pd.DataFrame(data) # 将Temp列转换为字符串类型,作为分类变量处理 df_melted['Temp'] = df_melted['Temp'].astype(str) barplot = sns.barplot(x='Temp', y='Value', hue='Measurement', data=df_melted, palette='viridis') for p in barplot.patches: height = p.get_height() x = p.get_x() + p.get_width() / 2. if height >= 0: barplot.text(x, height + 0.1, f'{height:.1f}', ha='center', va='bottom', fontsize=10, color='black', rotation=90) else: barplot.text(x, height - 0.1, f'{height:.1f}', ha='center', va='top', fontsize=10, color='black', rotation=90) plt.ylim([-25,25]) plt.show()
说明
转换后,Seaborn会将每个温度值(如"5"、"10"、"25"等)视为独立的分类标签,按原始数据中的顺序排列,不会再基于数值间隔生成额外的刻度位置,虚假零值也就消失了。
内容的提问来源于stack exchange,提问作者Quiescent
相关产品推荐
相关产品推荐

