You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SNS绘制分类x轴折线图报ConversionError错误如何解决?

错误原因
  • 核心问题:pd.cut生成的new_carat是分类(Categorical)类型,sns.countplot可以直接适配分类类型的x轴,但sns.lineplot默认不会对分类x对应的y值做聚合,直接传入原始数据集时,会尝试将所有零散的price值匹配分类轴的单位,最终触发转换失败报错。
  • 额外语法问题:你提供的代码中color = red的red没有加引号,属于未定义变量错误;plt.show遗漏了调用括号,不会触发绘图渲染。
解决方案

方案1:提前聚合数据(更稳定,可读性更高)

先按new_carat分组计算price的均值,再传入lineplot绘图,完整修正代码如下:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 原有分箱逻辑
df['new_carat'] = pd.cut(x=df['carat'], bins=[0, 0.49, 0.69, 0.99, 1.99, 3], 
                         labels=['<0.5', '0.5-0.69', '0.7-0.99', '1-1.99', '>2'])

# 新增:提前聚合计算每个分箱的平均价格
carat_price_avg = df.groupby('new_carat', observed=True)['price'].mean().reset_index()

# 绘制左侧计数柱状图
ax1 = sns.countplot(x='new_carat', data=df, palette='husl')
ax1.set_xlabel('Carat')
ax1.set_ylabel('Count')
ax1.set_title('Carat Count & Avg Price')

# 绘制右侧均价折线图
ax2 = ax1.twinx()
sns.lineplot(x='new_carat', y='price', data=carat_price_avg, color='red', ax=ax2, marker='o')
ax2.set_ylabel('Average Price')

plt.show()

方案2:直接在lineplot中指定聚合参数

如果不想单独做聚合操作,也可以直接在lineplot中指定estimator参数完成均值计算,无需提前分组:

# 仅替换原lineplot行即可
sns.lineplot(x='new_carat', y='price', data=df, color='red', ax=ax2, estimator='mean', errorbar=None)

内容的提问来源于stack exchange,提问作者Ads

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 23:06:03