如何巧妙地组合 .add_annotation 和 go.Layout?

How to combine .add_annotation and go.Layout in plotly?

请问如何将显示文本的命令与go.Layout结合起来?当存在 go.Layout() 时,命令 fig.add_annotation 停止工作。 go.Layout 包含许多功能;因此,我不想改变它。

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})


fig = px.scatter(df1, x='A', y='B')

fig.add_annotation(text="Absolutely-positioned annotation",
                  x=2.5, y=4.5, showarrow=False)

layout = go.Layout(
    template = "plotly_white",
    title="<b>O-C diagram</b>",
    font_family="Trebuchet",
    title_font_family="Trebuchet",
    title_font_color="Navy",
    xaxis_tickformat = "5.0",
    yaxis_tickformat = ".1f",
    xaxis2 = XAxis( 
        overlaying='x',
        side='top',
    ),
    legend=dict(
        yanchor="top",
        y=0.99,
        xanchor="left",
        x=0.83,
    font=dict(
        family="Trebuchet",
        size=20,
        color="black"
     ),
        bgcolor="LightGray",
        bordercolor="Black",
        borderwidth=0
     ),
    xaxis_title=r'<i>T</i>',
    yaxis_title=r'O',
    title_x=0.5,
    font=dict(
        family="Trebuchet",
        size=26,
        color="Black"
    ),
)

fig.layout = layout

fig.show()

这里的问题不是您使用的是:

layout = go.Layout(
    template = "plotly_white",
)

而是...

fig.layout = layout

...覆盖除 template.

之外的每个布局属性

如果您改为使用:

fig.update_layout(template = "plotly_white")

那么你会得到:

完整代码:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})


fig = px.scatter(df1, x='A', y='B')


fig.add_annotation(text="Absolutely-positioned annotation",
                  x=2.5, y=4.5, showarrow=False)

# layout = go.Layout(
#     template = "plotly_white",
# )

# fig.layout = layout
fig.update_layout(template = "plotly_white")
fig.show()

编辑 - 另一个建议

如果您出于某种原因需要坚持原来的设置,那么只需更改分配模板的顺序和图形的注释即可:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})


fig = px.scatter(df1, x='A', y='B')


layout = go.Layout(
    template = "plotly_white",
)

fig.layout = layout
fig.add_annotation(text="Absolutely-positioned annotation",
                  x=2.5, y=4.5, showarrow=False)

fig.show()