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

如何在Plotly中增大X/Y轴上重叠轨迹线的间距?

问题描述

背景

  • 已在Plotly官网、Plotly论坛及本论坛搜索解决方案3天,未找到有效方法
  • 曾参考以下StackOverflow问题:
    1. How to avoid overlapping text in a plotly scatter plot?
    2. Make X axis wider and Y axis narrower in plotly

问题现象

如附图所示:

  • 安哥拉、佛得角、莫桑比克、葡萄牙和圣多美和普林西比的轨迹线在Y轴重叠
  • 2022-2025年间所有国家的人口标记在X轴重叠

CSV数据

"Country","2022","2024","2025","2030","2040","2050"
"Angola","35.6M","37.9M","39M","45.2M","59M","74.3M"
"Brasil","210M","212M","213M","216M","219M","217M"
"Cabo Verde","520K","525K","527K","539K","557K","566K"
"Moçambique","32.7M","34.6M","35.6M","40.8M","52.1M","63.5M"
"Portugal","10.4M","10.4M","10.4M","10.3M","10.1M","9.8M"
"São Tomé and Príncipe","226K","236K","240K","265K","316K","365K"

实现代码

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

fig = go.Figure()
df = pd.read_csv('assets/csv/luso_pop_proj_who_data.csv')

for col in df.columns[1:]:
  df[col] = df[col].replace({"M": "e+06", "K": "e+03"}, regex = True).astype(float)
  
df_long = df.melt(id_vars = "Country", var_name = "Year", value_name = "Population")
df_long["Year"] = df_long["Year"].astype(int)

fig = px.line(
  df_long,
  color = "Country",
  height = 600,
  labels = 
  {
    "Country": "País",
    "Population": "Número de população", 
    "Year": "Ano"
  },
  template = "seaborn",
  text = "Population",
  title = "Projeção da população nos países lusófonos (2022-2050)",
  width = 1200,
  x = "Year",
  y = "Population",
)

fig.update_traces(
  hovertemplate = None,
  mode = "lines+markers+text",
  showlegend = True,
  textfont = dict(size = 15),
  textposition = "top center",
  texttemplate = "%{text:.3s}",
)

fig.update_layout(
  margin = dict(l = 0, r = 0, b = 10, pad = 0),
  hovermode = False
)

fig.show(
  config = config
)

测试过的无效配置

尝试过以下配置来增大轨迹线间距,但未达到预期效果:

fig = px.line(
  facet_row_spacing = 1,
)

fig.update_traces(
  line = dict(
    backoff = 10,
  ),
)

fig.update_xaxes(
  automargin = True,
  autorange = False,
  fixedrange = True,
  range = ['2020', '2050'],
)

fig.update_yaxes(
  automargin = True,
  fixedrange = True,
)

fig.update_layout(
  margin = dict(l = 0, r = 0, b = 10, pad = 0),
)

内容的提问来源于stack exchange,提问作者Oo'-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 01:37:04