如何使用单个Python列表在Plotly中绘制折线图(无需额外创建索引列表)
如何用单个列表在Plotly中绘制折线图(避免创建额外x轴列表)
嘿,这个需求很合理——没必要为了索引专门复制出一个x轴列表,Plotly有几种简洁的方式可以直接用单个列表生成你要的折线图:
方法1:直接传入y参数,让Plotly自动处理x轴
Plotly Express的px.line()在只接收y参数时,会自动将列表的索引作为x轴的取值,完全不用手动创建x轴数据:
import plotly.express as px import dash_core_components as dcc # 你的2020年每周事故数据列表 accident_data = [0, 0, 0, 2, 3, 4, 2, 3, 2, 2, 6, 4, 2, 1, 2, 1, 1, 3, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 2, 0, 0, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0] # 生成折线图 fig = px.line(y=accident_data, title="2020年每周事故数量变化趋势") # 自定义轴标签,让图表更清晰 fig.update_layout( xaxis_title="周数(索引对应)", yaxis_title="事故数量" ) # 在Dash中渲染图表 dcc.Graph(id='accident_trend_chart', figure=fig)
方法2:用range()生成x轴(更明确)
如果你想明确指定x轴的取值范围(比如强调周数从0到53),可以用range(len(accident_data))直接生成x轴序列,这个方式不会额外存储完整的x列表,内存效率更高:
fig = px.line( x=range(len(accident_data)), y=accident_data, title="2020年每周事故数量变化趋势" ) fig.update_layout( xaxis_title="周数", yaxis_title="事故数量" ) # Dash中使用 dcc.Graph(id='accident_trend_chart', figure=fig)
额外小提示
如果你的周数实际是从1开始(而不是索引的0),只需要把x轴的range改成range(1, len(accident_data)+1),这样x轴就会显示1到54,更符合实际的周数计数逻辑。
内容的提问来源于stack exchange,提问作者Bruce Banner
相关产品推荐
相关产品推荐

