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

Python Plotly子图标题样式修改、纵横比调整及高亮实现求助

解决子图高亮与正方形纵横比设置问题

需求说明

  • 对Run_2(第一行第二列)和Run_3(第二行第一列)子图进行高亮:
    • 修改标题为加粗并设置自定义颜色
    • 给子图添加黑色边框
  • 将所有子图调整为正方形纵横比

修改后完整代码

import numpy as np
from plotly.subplots import make_subplots
from math import exp
import plotly.graph_objects as go  # 补充导入graph_objects模块

fig = make_subplots(rows=2, cols=2, 
                    subplot_titles=("Run_1", "Run_2", "Run_3", "Run_4"), 
                    horizontal_spacing=0.04, vertical_spacing=0.09)

# 添加Run_1子图数据
x = np.linspace(0, 10, 1000)
y = np.array(list(map(lambda x: 1 / (1 + exp(-0.1 * x + 5)), x)))
fig.add_trace(
    go.Scatter(
        x=x,
        y=y,
        name=f'\N{Greek Small Letter Sigma}(x)',
    ),
    row=1, col=1
)

# 添加Run_2子图数据
x = np.where(np.random.randint(0, 2, 100)==1)[0]
fig.add_trace(
    go.Scatter(
        x=x,
        y=np.zeros_like(x),
        mode='markers', 
        marker=dict(symbol='circle-open', color='green', size=5),
    ),
    row=1, col=2
)

# 添加Run_3子图数据
x = np.where(np.random.randint(0, 2, 100)==1)[0]
fig.add_trace(
    go.Scatter(
        x=x,
        y=np.zeros_like(x),
        mode='markers', 
        marker=dict(symbol='circle-open', color='green', size=5),
    ),
    row=2, col=1
)

# 添加Run_4子图数据
x = np.where(np.random.randint(0, 2, 100)==1)[0]
fig.add_trace(
    go.Scatter(
        x=x,
        y=np.zeros_like(x),
        mode='markers', 
        marker=dict(symbol='circle-open', color='green', size=5),
    ),
    row=2, col=2
)

# -------------------------- 关键修改部分 --------------------------
# 1. 高亮Run_2和Run_3的标题:加粗+改颜色
# 子图标题按创建顺序存储在annotations列表中:Run_1(0)、Run_2(1)、Run_3(2)、Run_4(3)
fig.layout.annotations[1].update(font=dict(color='red', size=14, weight='bold'))
fig.layout.annotations[2].update(font=dict(color='red', size=14, weight='bold'))

# 2. 给Run_2和Run_3添加黑色边框
# Run_2对应xaxis2、yaxis2
fig.update_xaxes(linecolor='black', linewidth=2, row=1, col=2)
fig.update_yaxes(linecolor='black', linewidth=2, row=1, col=2)
# Run_3对应xaxis3、yaxis3
fig.update_xaxes(linecolor='black', linewidth=2, row=2, col=1)
fig.update_yaxes(linecolor='black', linewidth=2, row=2, col=1)

# 3. 设置所有子图为正方形纵横比
# 绑定x轴与y轴的缩放比例,确保两者缩放一致
for row in range(1, 3):
    for col in range(1, 3):
        fig.update_xaxes(scaleanchor=f'y{row*2-col+1}', scaleratio=1, constrain='domain', row=row, col=col)
        fig.update_yaxes(scaleanchor=f'x{row*2-col+1}', scaleratio=1, constrain='domain', row=row, col=col)

fig.show()

修改说明

  1. 标题高亮:Plotly子图标题存储在fig.layout.annotations列表中,直接修改对应索引的font属性即可设置颜色、粗细和字号。
  2. 添加边框:通过update_xaxes和update_yaxes指定目标子图的行和列,设置linecolor为黑色、linewidth为2实现边框效果。
  3. 正方形纵横比:使用scaleanchor绑定x轴与y轴的缩放基准,scaleratio=1保证两者缩放比例一致,配合constrain='domain'确保子图区域为正方形。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:25:17