【问题标题】:How to combine .add_annotation and go.Layout in plotly?如何在情节中结合 .add_annotation 和 go.Layout?
【发布时间】:2021-08-10 09:31:03
【问题描述】:

请问如何将显示文本的命令与 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()

【问题讨论】:

    标签: python text layout plotly


    【解决方案1】:

    这里的问题不是你正在使用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 2016-10-04
      • 2020-02-18
      • 1970-01-01
      • 2014-10-11
      • 1970-01-01
      相关资源
      最近更新 更多