Plotly柱状图比例异常咨询:90kg显示小于85kg
解决柱状图Y轴数值比例异常的问题
出现90kg柱形比85kg小的核心原因是Weight列的数据类型不是数值型,Plotly将其当作字符串/类别处理,而非按数值大小渲染。以下是具体修复步骤:
1. 检查并转换Weight列的数据类型
在处理ExamDate之后,添加代码确保Weight为数值类型:
# 转换Weight列为数值型,自动处理非数值内容为NaN(可根据需求调整errors参数) filtered_dataframe["Weight"] = pd.to_numeric(filtered_dataframe["Weight"], errors="coerce") # 可选:删除包含NaN的无效数据行 filtered_dataframe = filtered_dataframe.dropna(subset=["Weight"])
如果Weight列包含单位(如"90kg"),需要先提取数字部分再转换:
# 提取数字(假设单位在字符串末尾) filtered_dataframe["Weight"] = filtered_dataframe["Weight"].str.extract(r'(\d+\.?\d*)').astype(float)
2. 强制指定Y轴为线性刻度
在生成图表后,添加代码确保Y轴按数值线性渲染:
fig = px.bar( filtered_dataframe, x="ExamDate", y="Weight", color="Name", template="seaborn" ) fig.update_layout(barmode="group") # 强制Y轴为数值线性刻度,避免自动推断错误 fig.update_yaxes(type="linear") st.plotly_chart(fig, use_container_width=True, height=400)
验证方法
执行转换后,打印数据类型确认是否转换成功:
print(filtered_dataframe["Weight"].dtype) # 正常输出应为int64或float64
内容的提问来源于stack exchange,提问作者Francescom839
相关产品推荐
相关产品推荐

