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

Python Plotly如何设置让折线图线条延伸至坐标轴首尾两端

问题说明

创建包含2个子图的折线图,目标是让折线从x轴最左端起始位置延伸到最右端末尾位置,铺满整个x轴范围。
实际表现:

  • 绘制面积图时,添加stackgroup = "one"参数后,线条会自动延伸至坐标轴两端,无留白
  • 绘制普通折线图时,线条无法覆盖坐标轴首尾,两端存在多余留白

普通折线图未铺满效果:
普通折线图两端留白效果

添加stackgroup = "one"参数的面积图铺满效果:
面积图铺满坐标轴效果

可复现代码
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots 

rng = pd.date_range('2022-04-09', periods=20, freq='D')
np.random.seed(42)
first_df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) 
first_df['Type'] = 'A'

second_df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) 
second_df['Type'] = 'B'

final_df =  pd.concat([first_df,second_df]).sort_values(by = 'Date')
final_df['Is_Weekend'] = np.where((final_df['Date'].dt.weekday == 5), 1, 0 )

A_df = final_df[final_df['Type']=='A']
B_df = final_df[final_df['Type']=='B']

fig = make_subplots(rows=2, cols=1,
                    shared_xaxes=True)


fig.add_trace(go.Scatter(x=A_df['Date'], 
                         y = A_df['Val'], 
                         line_color = 'orange',
                         mode = 'lines+markers',
                         showlegend = True, name = "A"),
              row=1, col=1,
              secondary_y = False)


fig.add_trace(go.Scatter(x=B_df['Date'], 
                         y = B_df['Val'], 
                         line_color = 'blue',
                         mode = 'lines+markers',
                         showlegend = True, name = "B"),
              row=2, col=1,
              secondary_y = False)


fig.update_layout(legend_traceorder="reversed", hovermode = "x unified", yaxis_tickformat = ".1%")

fig.show()
原因与解决方案

出现该差异的核心原因是:Plotly默认会给连续型坐标轴(含日期轴)自动添加首尾内边距,避免数据点贴到坐标轴边框上;而启用stackgroup参数绘制堆叠面积图时,Plotly会自动关闭该默认边距,将坐标轴范围严格对齐到数据的最小、最大值,因此会呈现铺满效果。

要让普通折线图实现相同的铺满效果,只需要手动指定所有x轴的范围为数据的起止值,覆盖默认的自动边距即可。在原有代码fig.show()之前添加如下代码:

# 获取x轴数据的起止边界
x_min = final_df['Date'].min()
x_max = final_df['Date'].max()
# 统一设置所有子图x轴范围,消除两端留白
fig.update_xaxes(range=[x_min, x_max])

添加后运行代码,折线即可从x轴最左端延伸到最右端,和堆叠面积图的轴范围表现完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 23:06:09