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

使用Plotly绘制堆叠柱状图时出现ValueError错误的解决方法

修复Plotly堆叠柱状图的ValueError问题

错误原因

出现ValueError: could not convert string to float: 'wide_variable_0',是因为Plotly Express的px.bar更适配长格式数据,而你的DataFrame是宽格式(行是apple/ichigo等类别,列是A-J维度),直接传入时系统无法正确识别分组维度与数值列的对应关系,导致自动生成的临时列名被误判为数值类型处理。

修复步骤

1. 数据格式转换

先将宽格式DataFrame转为长格式,同时把索引(apple/ichigo等)转为独立列:

import pandas as pd

# 假设你的原始DataFrame名为df
# 1. 将索引转为列,命名为分组维度(比如"fruit")
df = df.reset_index().rename(columns={"index": "fruit"})
# 2. 转成长格式:拆分列维度(A-J)为独立列,保留数值列
long_df = df.melt(id_vars="fruit", var_name="category", value_name="percentage")

如果你的百分比数值是带%的字符串,需要先转成数值类型:

# 去除百分号并转为浮点型
long_df["percentage"] = long_df["percentage"].str.replace("%", "", regex=True).astype(float)

2. 绘制堆叠柱状图

用转换后的长格式数据调用px.bar,指定堆叠模式:

import plotly.express as px

fig = px.bar(
    long_df,
    x="category",  # x轴为A-J列
    y="percentage",  # y轴为百分比数值
    color="fruit",  # 堆叠部分按apple/ichigo等区分颜色
    barmode="stack"  # 开启堆叠模式
)
fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:50:07