在Plotly Express时间轴中使用自定义时间格式

2024-10-03 23:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用plotly express创建自定义时间轴图形对象,我希望编辑x(时间)轴以显示不同的时间格式,但它只允许“datetime”。是否有任何方法可以在使用时间线对象时使用自定义时间类型?是否有更好的框架,例如matplotlib或其他什么


Tags: 对象方法框架图形编辑类型datetimematplotlib
1条回答
网友
1楼 · 发布于 2024-10-03 23:19:53

可以使用plotly自定义时间格式,请参见plotly documentation。此处显示的示例使用px.line(),但格式化使用px.timeline()的方式相同

例如:

presidents = pd.DataFrame([{"name": "Clinton", "start": '1993-01-20', 'end': '2001-01-20'},
                           {"name": "Bush", "start": '2001-01-20', 'end': '2009-01-20'},
                           {"name": "Obama", "start": '2009-01-20', 'end': '2017-01-20'},
                           {"name": "Trump", "start": '2017-01-20', 'end': '2021-01-20'}
                          ])

fig = px.timeline(presidents,
                  x_start="start",
                  x_end="end",
                  y="name"
                 )
fig.update_xaxes(
    dtick="M48",   # display x-ticks every 24 months months
    tickformat="Date:%Y-%m-%d"  # date format
) 
fig.show()

这使得:

plotly timeline

相关问题 更多 >