如何在Plotly Express中设置facet_row生成的特定子图高度(中国行高加倍)
调整Plotly Facet Row子图行高(China子图2倍高)
要实现China对应的子图行高为其他子图的2倍,需要手动修改子图的domain参数(控制子图在画布中的垂直范围),因为Plotly Express默认会给所有facet子图分配等高布局。
实现步骤:
- 创建原始的时间线facet子图。
- 定位到对应China的子图轴对象。
- 计算各子图的高度占比(China占2份,其他各占1份)。
- 重新分配每个子图的垂直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
相关产品推荐
相关产品推荐

