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

Plotly多Y轴散点图问题咨询及代码修改指导

多Y轴散点图问题修复方案

针对你遇到的5个问题,以下是具体修改方案和完整代码:

问题修复说明

  • 散点无颜色:明确给每个散点轨迹指定marker.color,并与对应Y轴标题颜色匹配,避免样式冲突。
  • Y轴文本重叠:调整左右Y轴的position参数拉开间距,同时缩小X轴domain范围,给轴标题留出足够展示空间。
  • Y轴未展示全部数值:通过autorange=True让Plotly自动适配数据范围,或手动指定range参数固定数值区间。
  • X轴显示完整日期:设置tickformat为%Y年%m月%d日,开启tickmode='linear'尽可能多生成日期刻度,同时旋转刻度避免重叠。
  • Y轴显示原始数值:给目标Y轴添加tickformat=',d',强制以整数格式显示,禁用K/M类缩写。

修改后的完整代码

import plotly.graph_objects as go

fig = go.Figure()

# 添加散点轨迹,确保marker颜色明确设置
fig.add_trace(go.Scatter(
    x=l1.DATE,
    y=l1.CODE,
    name="yaxis1数据",
    mode='markers',
    yaxis="y1",
    marker={'color': '#1f77b4'}  # 与yaxis1标题颜色一致
))

fig.add_trace(go.Scatter(
    x=l2.DATE,
    y=l2.CODE,
    name="yaxis2数据",
    mode='markers',
    yaxis="y2",
    marker={'color': '#ff7f0e'}  # 与yaxis2标题颜色一致
))

fig.add_trace(go.Scatter(
    x=l3.DATE,
    y=l3.CODE,
    name="yaxis3数据",
    mode='markers',
    yaxis="y3",
    marker={'color': '#d62728'}  # 与yaxis3标题颜色一致
))

fig.add_trace(go.Scatter(
    x=l4.DATE,
    y=l4.CODE,
    name="yaxis4数据",
    mode='markers',
    yaxis="y4",
    marker={'color': '#9467bd'}  # 与yaxis4标题颜色一致
))

# 更新轴配置,解决所有问题
fig.update_layout(
    xaxis=dict(
        domain=[0.2, 0.8],  # 缩小X轴范围,给左右Y轴留空间
        tickformat='%Y年%m月%d日',  # 设置完整日期格式
        tickmode='linear',  # 线性生成刻度,尽可能多展示日期
        tickangle=45,  # 旋转刻度避免重叠
        showgrid=True
    ),
    yaxis=dict(
        title="yaxis1标题",
        titlefont=dict(color="#1f77b4"),
        tickfont=dict(color="#1f77b4"),
        autorange=True,  # 自动适配数据范围,展示全部数值
        tickformat=',d'  # 强制显示原始整数,禁用K/M缩写
    ),
    yaxis2=dict(
        title="yaxis2标题",
        titlefont=dict(color="#ff7f0e"),
        tickfont=dict(color="#ff7f0e"),
        anchor="free",
        side="left",
        position=0.08,  # 调整左侧轴位置,避免重叠
        autorange=True
    ),
    yaxis3=dict(
        title="yaxis3标题",
        titlefont=dict(color="#d62728"),
        tickfont=dict(color="#d62728"),
        anchor="free",
        side="right",
        position=0.92,  # 调整右侧轴位置,避免重叠
        autorange=True
    ),
    yaxis4=dict(
        title="yaxis4标题",
        titlefont=dict(color="#9467bd"),
        tickfont=dict(color="#9467bd"),
        anchor="free",
        side="right",
        position=0.85,
        autorange=True
    ),
    title_text="多Y轴散点图示例",
    width=1200,  # 加宽图表,给更多空间展示轴和刻度
    height=600
)

fig.show()

补充说明

  • 若需手动固定Y轴范围,可将autorange=True替换为range=[数据最小值, 数据最大值],例如range=[l1.CODE.min(), l1.CODE.max()]。
  • 若X轴日期仍有重叠,可进一步增大tickangle(如设为60)或加宽图表宽度。
  • 散点颜色与对应Y轴颜色统一,提升图表视觉关联性。

内容的提问来源于stack exchange,提问作者user14269252

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:00:02