Plotly中fig.update_layout的shapes参数传数组报错求助
问题原因与解决方法
核心问题
你往shapeArray中添加的是字符串形式的字典文本,但Plotly的shapes参数要求传入的是Python字典对象组成的列表,而非字符串。错误提示里的无效元素正是这些带引号的字符串,Plotly无法解析这类格式。
修复代码
将添加元素的代码改为直接添加字典对象,无需加引号和转义:
shapeArray = [] # 直接传入字典,不是字符串 shapeArray.append(dict(x0='2021-10-04', x1='2021-10-04', y0=0, y1=1, xref='x', yref='paper', line_width=2)) shapeArray.append(dict(x0='2021-11-22', x1='2021-11-22', y0=0, y1=1, xref='x', yref='paper', line_width=2))
调用update_layout的代码保持不变即可,此时shapeArray内的元素都是Plotly可识别的字典对象:
fig.update_layout( title='purchases', yaxis_title='price', shapes=shapeArray, annotations = [dict(x='2021-10-04', y=0.05, xref='x', yref='paper', showarrow=False, xanchor='left', text='buy0'),], )
动态添加扩展
如果需要根据业务需求动态生成任意数量的形状,可以通过循环构建列表:
# 示例:从日期列表批量生成竖线形状 date_list = ['2021-10-04', '2021-11-22', '2021-12-10'] shapeArray = [] for date in date_list: shape = dict( x0=date, x1=date, y0=0, y1=1, xref='x', yref='paper', line_width=2 ) shapeArray.append(shape)
这种方式可以灵活生成任意数量的形状,且每个元素都是符合要求的字典对象。
内容的提问来源于stack exchange,提问作者coltenx
相关产品推荐
相关产品推荐

