Plotly Express如何实现非均匀日期的条形图紧挨显示?
问题:Plotly Express日期分布不均时让条形图紧挨在一起
我有一个日期分布不均匀的数据集,绘制条形图时因为日期间隔不均,条形之间存在间距。想忽略数据值之间的日期,让条形紧挨在一起,使用Plotly Express的代码如下:
ecc_duration_by_name = df_selection.groupby(by=["Date"]).mean()[["Eccentric Duration [ms] "]] fig_ecc_duration = px.bar( ecc_duration_by_name, x=ecc_duration_by_name.index, y="Eccentric Duration [ms] ", title="<b>Eccentric Duration</b>", color_discrete_sequence=["#3679ff"] * len(ecc_duration_by_name), template="plotly_white", ) fig_ecc_duration.update_layout( plot_bgcolor="rgba(0,0,0,0)", yaxis=(dict(showgrid=False)), )
当前效果:条形图中条形因日期间隔存在空白间距
期望效果:所有条形紧密排列,无间隔
解决方案
核心思路是让Plotly将x轴的日期视为独立类别,而非时间序列数据,这样就会忽略日期之间的实际间隔,让条形紧挨在一起。有两种实现方式:
方式1:将日期索引转为字符串类型
直接在px.bar的x参数中把日期索引转换为字符串,Plotly会自动将其当作类别处理:
ecc_duration_by_name = df_selection.groupby(by=["Date"]).mean()[["Eccentric Duration [ms] "]] fig_ecc_duration = px.bar( ecc_duration_by_name, x=ecc_duration_by_name.index.astype(str), # 转换日期为字符串 y="Eccentric Duration [ms] ", title="<b>Eccentric Duration</b>", color_discrete_sequence=["#3679ff"] * len(ecc_duration_by_name), template="plotly_white", ) fig_ecc_duration.update_layout( plot_bgcolor="rgba(0,0,0,0)", yaxis=(dict(showgrid=False)), xaxis_title="Date" # 手动设置x轴标题,避免转换后标题丢失 )
方式2:设置x轴类型为category
保留日期索引的类型,通过update_xaxes强制将x轴设置为类别型:
ecc_duration_by_name = df_selection.groupby(by=["Date"]).mean()[["Eccentric Duration [ms] "]] fig_ecc_duration = px.bar( ecc_duration_by_name, x=ecc_duration_by_name.index, y="Eccentric Duration [ms] ", title="<b>Eccentric Duration</b>", color_discrete_sequence=["#3679ff"] * len(ecc_duration_by_name), template="plotly_white", ) fig_ecc_duration.update_layout( plot_bgcolor="rgba(0,0,0,0)", yaxis=(dict(showgrid=False)), ) fig_ecc_duration.update_xaxes(type='category') # 设置x轴为类别型
两种方法都能实现你想要的条形紧密排列效果。
内容的提问来源于stack exchange,提问作者Markus Fürst
相关产品推荐
相关产品推荐

