Seaborn堆叠图绘制报错:Cylinders数据过滤及箱线图问题
解决Seaborn堆叠图(箱线图+直方图)的数据过滤ValueError问题
错误根源
触发ValueError的核心原因是布尔运算优先级问题:Python中按位或运算符|的优先级高于相等运算符==,导致原代码df2['Cylinders'] == 8 | df2['Cylinders'] == 4被错误解析为df2['Cylinders'] == (8 | df2['Cylinders']) == 4,生成歧义的布尔Series,触发Pandas的真值判断报错。
修正后的完整代码
import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt # 读取数据 df2 = pd.read_csv('/content/drive/MyDrive/mpg-Theo_Tuggle.csv') # 创建堆叠图布局 f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (.15, .85)}) sns.set(style="ticks") # 添加文本(修正原代码中ax未定义的问题) text = 'Theo' f.text(0.7, 0.6, text, fontsize=10, transform=f.transFigure) # 定义箱线图异常点样式 flierprops = dict(marker='o', markersize=4, markerfacecolor='none', linestyle='none', markeredgecolor='gray') # 正确过滤4、8缸数据(两种可选写法) # 写法1:用括号包裹每个条件,确保逻辑或运算正确 df_filtered = df2[(df2['Cylinders'] == 8) | (df2['Cylinders'] == 4)] # 写法2:用isin更简洁直观 # df_filtered = df2[df2['Cylinders'].isin([4, 8])] # 绘制直方图:仅展示4、8缸的Acceleration数据 sns.histplot(data=df2[df2['Cylinders']==8], x="Acceleration", ax=ax_hist, kde=True) sns.histplot(data=df2[df2['Cylinders']==4], x="Acceleration", ax=ax_hist, kde=True, color="orange") # 绘制箱线图:X轴为Acceleration,Y轴为Cylinders(仅展示4、8缸) ax = sns.boxplot(y=df_filtered.Cylinders, x=df_filtered.Acceleration, ax=ax_box, orient='h', fliersize=4, width=0.5, linewidth=1, flierprops=flierprops) # 美化图形 ax_box.set(yticks=[]) ax_box.set(xticks=[]) ax_box.set_xlabel('') sns.despine(ax=ax_hist) sns.despine(ax=ax_box, left=True, bottom=True) plt.show()
关键修正点说明
- 数据过滤修正:通过括号包裹单个条件或使用
isin()方法,确保逻辑运算优先级正确,准确筛选出4、8缸的汽车数据。 - 文本位置修正:原代码在创建子图前调用
ax.text()会导致ax未定义错误,改为使用画布对象f.text()添加文本。 - 箱线图参数调整:将过大的
width=15改为合理值width=0.5,避免图形元素超出显示范围;同时调整fliersize匹配异常点样式定义。 - 逻辑一致性:箱线图和直方图均仅展示4、8缸的
Acceleration数据,符合需求。
内容的提问来源于stack exchange,提问作者theocodes03
相关产品推荐
相关产品推荐

