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

如何在Plotly Express中设置facet_row生成的特定子图高度(中国行高加倍)

调整Plotly Facet Row子图行高(China子图2倍高)

要实现China对应的子图行高为其他子图的2倍,需要手动修改子图的domain参数(控制子图在画布中的垂直范围),因为Plotly Express默认会给所有facet子图分配等高布局。

实现步骤:

  1. 创建原始的时间线facet子图。
  2. 定位到对应China的子图轴对象。
  3. 计算各子图的高度占比(China占2份,其他各占1份)。
  4. 重新分配每个子图的垂直domain范围。

完整代码:

import plotly.express as px 
import pandas as pd 

df = pd.DataFrame([
    dict(team='Wolfs', start='2004-05-23', end='2006-05-24', country='Russia'), 
    dict(team='Lions', start='2007-07-05', end='2009-07-06', country='USA'), 
    dict(team='Crows', start='2001-08-09', end='2003-08-11', country='USA'), 
    dict(team='Elephants', start='2010-02-14', end='2012-02-15', country='China') 
])

# 创建原始facet子图
fig = px.timeline(df, x_start='start', x_end='end', y='team', facet_row='country')

# 定位对应China的子图索引
target_country = 'China'
# 获取所有子图的y轴对象(数量等于唯一country的数量)
yaxes = [fig.layout.yaxis, fig.layout.yaxis2, fig.layout.yaxis3]
target_idx = None
for idx, yaxis in enumerate(yaxes):
    if yaxis.title.text == target_country:
        target_idx = idx
        break

# 计算总高度份数:其他子图各1份,China占2份
num_subplots = len(yaxes)
total_parts = (num_subplots - 1) * 1 + 2

# 定义每个子图的高度权重
height_weights = [2 if i == target_idx else 1 for i in range(num_subplots)]

# 重新计算每个子图的垂直domain范围(从上到下分配)
current_top = 1.0
new_domains = []
for weight in height_weights:
    height_ratio = weight / total_parts
    current_bottom = current_top - height_ratio
    new_domains.append([current_bottom, current_top])
    current_top = current_bottom

# 应用新的domain到每个子图的y轴
for yaxis, domain in zip(yaxes, new_domains):
    yaxis.domain = domain

fig.show()

代码说明:

  • 通过遍历子图的y轴标题,精准定位对应China的子图索引。
  • 按「China占2份,其他子图各占1份」的比例计算总高度份数,再分配每个子图的垂直占比。
  • 修改每个子图的domain参数,重新定义它们在画布中的垂直位置和高度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:57:49