Python Plotly堆叠柱状图轨迹未正确堆叠问题求助
解决Plotly堆叠柱状图数据不显示的问题
核心问题出在y轴数据的类型:你定义的cy和ly是带$符号和千分位逗号的字符串,Plotly无法将这类字符串识别为可计算的数值,导致堆叠逻辑无法正常工作,2023年的柱状图因此无法显示。
修复步骤及代码
- 把字符串格式的金额转换为浮点型数值,去掉
$和逗号后再转数字 - 修正
trace2里的语法错误(多了一个闭合括号)
修改后的完整代码:
import plotly.graph_objects as go def convert_currency_to_float(currency_str): # 去掉$和逗号,转换为浮点型 return float(currency_str.replace('$', '').replace(',', '')) branches = ['AMN', 'ACF'] cy = ["$33,532.80","$29,798.24"] ly = ["$35,612.46", "$15,966.40"] # 转换数值类型,同时保留原字符串用于文本显示 cy_numeric = [convert_currency_to_float(val) for val in cy] ly_numeric = [convert_currency_to_float(val) for val in ly] trace1 = go.Bar( x = branches, y = cy_numeric, text=cy, textposition='auto', name = "2023-05-25" ) trace2 = go.Bar( x = branches, y = ly_numeric, text=ly, textposition='auto', name = "2022-05-25" ) data = [trace1, trace2] layout = go.Layout(barmode = 'stack') fig = go.Figure(data = data, layout = layout) fig.show()
关键说明
- 转换后的数值用于y轴的堆叠计算,确保Plotly能正确处理柱状图的堆叠逻辑
- 原字符串保留在
text参数中,保证图表显示的文本还是带格式的金额 - 修复了
trace2末尾多余的),避免语法报错
内容的提问来源于stack exchange,提问作者Justin Carlson
相关产品推荐
相关产品推荐

