如何在绘图中组合.添加\注释和go.布局?

2024-07-07 08:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: import命令gotitleasfigannotationplotly
1条回答
网友
1楼 · 发布于 2024-07-07 08:12:04

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

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

但更确切地说

fig.layout = layout

…覆盖除template之外的所有布局属性

如果您改为使用:

fig.update_layout(template = "plotly_white")

然后你会得到:

enter image description here

完整代码:

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

相关问题 更多 >