Skip to main content
 首页 » 编程设计

python之如何在 Plotly (Python) 中分别注释每个子图

2025年05月04日10zlslch

我正在尝试将一个单独的注释对象与 Plotly (Python) 中的每个子图相关联,该怎么做?

我尝试过的

我正在这样设置 plotly :

from plotly import tools 
fig = tools.make_subplots(rows=2, cols=1) 
fig.append_trace(traces[0], 1, 1) 
fig.append_trace(traces[1], 2, 1) 

每条轨迹是这样形成的:

import plotly.graph_objs as go 
traces[0] = go.Scatter( 
            x=[1,2,3,4], 
            y=[4,4,2,1], 
            mode='markers' 
        ) 

我知道我可以通过以下方式分别访问每个子图的 x 轴:

fig['layout']['xaxis1'].update(title='hello1') 
fig['layout']['xaxis2'].update(title='hello2') 

但是我怎样才能访问每个子图的注释呢?我尝试了“annotations1”和“annotation1”,但没有成功。我还尝试通过“layout1”访问子图 1 的布局,如下所示:

fig['layout1'][...].update(...) 

这也不起作用。

请您参考如下方法:

1) 您可以通过设置xref 和yref 与子图轴id,例如x1 和 来为特定的子图分配注释y1 表示 subplot1 的 x 轴和 y 轴,如以下示例和 link 上的更多示例所示

fig['layout'].update( 
    annotations=[ 
    dict( 
        x=2, y=2, # annotation point 
        xref='x1',  
        yref='y1', 
        text='dict Text', 
        showarrow=True, 
        arrowhead=7, 
        ax=10, 
        ay=70 
    ), 
    dict( 
        ... 
        # if have multiple annotations 
    ) 
]) 

2) 赋值后,可以通过

访问注解
fig['layout']['annotations'] 

这将返回一个字典项目列表:

[{'xref': 'x2', 'arrowhead': 7, 'yref': 'y2', 'text': 'dict Text', 'ay': 40, 'ax': 10, 'y': -1.9491807521563174, 'x': 0.77334098360655923, 'showarrow': True}, {'xref': 'x2', 'arrowhead': 7, 'yref': 'y2', 'text': 'dict Text', 'ay': -40, 'ax': 10, 'y': -0.0041268527747384542, 'x': 1.1132422279202281, 'showarrow': True}] 

希望这能有所帮助;)