如何让Plotly Express折线图仅显示日期,隐藏正午标记?
解决Plotly Express折线图X轴显示多余正午(12pm)标记的问题
使用Plotly Express绘制折线图时,X轴出现了数据集中不存在的正午(12pm)标记,需要仅显示日期维度,隐藏该标记。
原代码
df_combined = df_combined.sort_values(by='sold_date', ascending=True) df_smt = df_combined.loc[df_combined['model'] == 'Adapt'].groupby('date').agg({'price': 'sum', 'sold_date': 'count'}).reset_index() fig = px.line(df_smt, x='date', y='price', title='Adapt') fig.show()
问题图表截图

解决方案
方法1:更新布局设置X轴日期格式
通过update_layout指定X轴刻度的日期格式,强制只显示日期部分:
df_combined = df_combined.sort_values(by='sold_date', ascending=True) df_smt = df_combined.loc[df_combined['model'] == 'Adapt'].groupby('date').agg({'price': 'sum', 'sold_date': 'count'}).reset_index() fig = px.line(df_smt, x='date', y='price', title='Adapt') # 设置X轴刻度为纯日期格式 fig.update_layout(xaxis={'tickformat': '%Y-%m-%d'}) fig.show()
方法2:直接配置X轴类型与格式
在绘图后通过update_xaxes明确设置X轴为日期类型并指定显示格式:
df_combined = df_combined.sort_values(by='sold_date', ascending=True) df_smt = df_combined.loc[df_combined['model'] == 'Adapt'].groupby('date').agg({'price': 'sum', 'sold_date': 'count'}).reset_index() fig = px.line(df_smt, x='date', y='price', title='Adapt') # 定义X轴类型为日期,设置显示格式 fig.update_xaxes(type='date', tickformat='%Y-%m-%d') fig.show()
原理说明
出现多余的12pm标记是因为Plotly默认会根据数据的时间精度自动生成刻度,即便你的date列是纯日期类型,Plotly仍可能以带时间的格式渲染刻度。通过指定tickformat为纯日期格式(如%Y-%m-%d),可以强制X轴仅显示日期部分,隐藏不必要的时间标记。
内容的提问来源于stack exchange,提问作者oToMaTiX
相关产品推荐
相关产品推荐

