如何在Plotly的make_subplots中增大雷达图标题与绘图区域的间距?
增大雷达图子标题与绘图区域的间距
针对使用make_subplots创建的多雷达图,默认子图标题与绘图区域间距过近的问题,可通过以下两种方法调整:
方法一:修改默认子图标题位置
原代码通过subplot_titles生成的标题属于布局中的annotations元素,直接修改这些元素的Y轴位置即可拉开间距:
在fig.show()前添加以下代码:
# 调整子图标题位置,增大与雷达图的间距 for idx, ann in enumerate(fig.layout.annotations): # 第一行子图标题向上偏移 if idx < 2: ann.y = 1.08 # 默认Y值为1.0,数值越大间距越大 # 第二行子图标题向上偏移 else: ann.y = 0.58 # 默认Y值为0.5,数值越大间距越大 ann.yanchor = "bottom" # 设置标题锚点为底部,确保偏移方向正确
方法二:手动添加自定义子图标题
若需要更灵活的控制,可放弃subplot_titles参数,手动添加注释作为子图标题:
- 创建子图时移除
subplot_titles参数:
fig = make_subplots( rows=2, cols=2, specs=[ [{"type": "polar"}]*2, [{"type": "polar"}]*2 ] )
- 添加完所有trace后,自定义标题:
# 定义每个子图标题的画布位置(0=左/下,1=右/上) title_positions = [(0.25, 0.95), (0.75, 0.95), (0.25, 0.45), (0.75, 0.45)] for title, (x, y) in zip(df.columns, title_positions): fig.add_annotation( x=x, y=y, text=title, showarrow=False, xref="paper", yref="paper", font=dict(size=14), yanchor="bottom" )
调整title_positions中的Y值即可控制间距,数值越大标题越靠上,间距越大。
完整修改后的代码(方法一示例)
import pandas as pd import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots import plotly.io as pio pio.renderers.default = "browser" # 创建随机数据集 np.random.seed(123) df = pd.DataFrame( np.random.randint(0, 100, size=(4, 4)), columns=["M1", "M2", "M3", "M4"], index=list("ABCD") ) # 定义每个雷达图的子图位置 n_rads = len(df.columns) positions = [(i//(n_rads//2)+1, i%(n_rads//2)+1) for i in range(n_rads)] # 计算每列数据的最大最小值,用于设置雷达图范围 mm_cols = df.apply(lambda x: (min(x), max(x))).values.T # 创建2行2列的子图布局 fig = make_subplots( rows=2, cols=2, specs=[ [{"type": "polar"}]*2, [{"type": "polar"}]*2 ], subplot_titles=df.columns, ) # 逐个添加雷达图轨迹 for idx, col in enumerate(df.columns): fig.add_trace( go.Scatterpolar( r=df[col], theta=df.index, fill='toself', name=col ), row=positions[idx][0], col=positions[idx][1] ) fig.update_layout( polar=dict( radialaxis=dict( visible=True, range=mm_cols[idx] ) ), showlegend=True ) # 调整子图标题与绘图区域的间距 for idx, ann in enumerate(fig.layout.annotations): if idx < 2: ann.y = 1.08 else: ann.y = 0.58 ann.yanchor = "bottom" fig.show()
内容的提问来源于stack exchange,提问作者Temp
相关产品推荐
相关产品推荐

