You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly中设置X轴范围并调整刻度为每2年显示一次

问题

需要调整Plotly折线图的X轴:当前数据包含2012年至2022年10月的每日时间数据,要求X轴覆盖全部年份范围,但仅每2年显示一个刻度。原代码如下:

import plotly.express as px

fig = px.line(data_SPY, y=['Close'], line_shape='linear', color_discrete_sequence=["#930435"],
              labels={'value': "Precio", 'Date': "Fecha"})
fig.update_layout(
    showlegend=False,
    title= 'Precio SPY ETF',
    font_color= "#000000",
    font_family="Tahoma",
    xaxis = dict(
        tickangle = 0,
        ticklabelstep=1,
        showgrid=True,   
    ), 
    yaxis = dict(
        showgrid=True
    ), 
   legend = dict(
     orientation='v'
   ), 
    paper_bgcolor='#FFFFFF'
)
fig.show(renderer="iframe")
解决方案

直接修改xaxis的配置,利用Plotly的时间轴刻度控制参数实现需求,修改后的完整代码如下:

import plotly.express as px

fig = px.line(data_SPY, y=['Close'], line_shape='linear', color_discrete_sequence=["#930435"],
              labels={'value': "Precio", 'Date': "Fecha"})
fig.update_layout(
    showlegend=False,
    title= 'Precio SPY ETF',
    font_color= "#000000",
    font_family="Tahoma",
    xaxis = dict(
        tickangle = 0,
        showgrid=True,
        # 设置时间刻度间隔为2年(24个月)
        dtick='M24',
        # 刻度仅显示年份格式
        tickformat='%Y',
        # 强制X轴覆盖数据的完整时间范围
        range=[data_SPY['Date'].min(), data_SPY['Date'].max()]
    ), 
    yaxis = dict(
        showgrid=True
    ), 
    legend = dict(
        orientation='v'
    ), 
    paper_bgcolor='#FFFFFF'
)
fig.show(renderer="iframe")

关键参数说明

  • dtick='M24':指定时间刻度间隔为24个月(即2年),Plotly会自动根据时间序列生成对应刻度
  • tickformat='%Y':设置刻度文本仅显示年份,简化X轴显示
  • range=[data_SPY['Date'].min(), data_SPY['Date'].max()]:确保X轴范围覆盖数据的最早和最晚日期,完整展示所有年份

注意:如果你的Date列还未转换为datetime类型,需先执行转换:

data_SPY['Date'] = pd.to_datetime(data_SPY['Date'])

内容的提问来源于stack exchange,提问作者Juan Pedro Lazcano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:45:37