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

时间:2016-12-30 20:23:50

标签: 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)

每条迹线的形成如下:

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(...)

这也不起作用。

2 个答案:

答案 0 :(得分:5)

1)您可以通过设置xrefyref子点轴ID来为特定子图分配注释,例如x1y1表示x轴和y轴subplot1,如下面的示例所示,以及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}]

希望这可以提供帮助;)

答案 1 :(得分:3)

它也可以与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()