如何在Plotly(Python)中单独注释每个子图

den*_*var 1 python plot plotly

我试图将一个单独的注释对象与Plotly(Python)中的每个子图关联起来,如何做到这一点?

我尝试了什么

我正在设置这样的情节:

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)
Run Code Online (Sandbox Code Playgroud)

每条迹线的形成方式如下:

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

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

fig['layout']['xaxis1'].update(title='hello1')
fig['layout']['xaxis2'].update(title='hello2')
Run Code Online (Sandbox Code Playgroud)

但是如何访问每个子图的注释?我试过"annotations1"和"annotation1",没有运气.我还尝试通过"layout1"访问子图1的布局,如下所示:

fig['layout1'][...].update(...)
Run Code Online (Sandbox Code Playgroud)

这也不起作用.

小智 9

1)您可以通过设置xrefyref子图轴id 来为特定子图分配注释,例如x1y1表示subplot1的x轴和y轴,如下面的示例所示,更多链接

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
    )
])
Run Code Online (Sandbox Code Playgroud)

2)分配完成后,您可以访问注释

fig['layout']['annotations']
Run Code Online (Sandbox Code Playgroud)

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

[{'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}]
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助;)


小智 8

如果您将子图作为注释列表中的元素,它也可以与 update() 一起使用。

from plotly.subplots import make_subplots
import plotly.graph_objects as go

# create figure with subplots
fig = make_subplots(rows=1, cols=2, subplot_titles = ['title1','title2'])

fig.add_trace(
    go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
    row=1, col=1
)

fig.add_trace(
    go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
    row=1, col=2
)

fig.update_layout(height=600, width=800, title_text="Subplots")

fig.show()

# to change subtitle, address subplot
fig['layout']['annotations'][0].update(text='your text here');

fig.show()
Run Code Online (Sandbox Code Playgroud)