gpt4 book ai didi

python - plotly 图例标题

转载 作者:太空狗 更新时间:2023-10-29 17:16:51 26 4
gpt4 key购买 nike

我希望能够在以下代码中为图例添加标题。然而,看着 docs ,我不认为有这种方法。

import plotly.plotly as py
import plotly.graph_objs as go

trace0 = go.Scatter(
x=[1, 2, 3, 4, 5],
y=[1, 2, 3, 4, 5],
)

trace1 = go.Scatter(
x=[1, 2, 3, 4, 5],
y=[5, 4, 3, 2, 1],
)

data = [trace0, trace1]
fig = go.Figure(data=data)

py.iplot(fig, filename='default-legend')

最佳答案

更新:

如果不定义图例但具有注释定位属性,请使用以下代码。

import plotly.offline as py_offline
import plotly.graph_objs as go
py_offline.init_notebook_mode()

trace0 = go.Scatter(
x=[1, 2, 3, 4, 5],
y=[1, 2, 3, 4, 5],
)

trace1 = go.Scatter(
x=[1, 2, 3, 4, 5],
y=[5, 4, 3, 2, 1],
)

data = [trace0, trace1]
layout = go.Layout(
annotations=[
dict(
x=1.12,
y=1.05,
align="right",
valign="top",
text='Legend Title',
showarrow=False,
xref="paper",
yref="paper",
xanchor="center",
yanchor="top"
)
]
)
fig = go.Figure(data=data, layout = layout)

py_offline.iplot(fig)

注意事项:

  1. 你需要定义xy使用此方法的注释位置,用于不同的图例。

  2. 您可以在 text 中使用 html属性(例如:text='Legend Title<br>kinda lengthy',)

上次尝试:

另一种方法是创建图例并使用注释将标题添加到图例中。前提是您不在可编辑模式下使用图形。所以在下面的示例中,图例设置为 x=0 和 y=1,因为我希望我的图例标题高于我的实际图例,我将注释位置设置为 x = 0,y = 1.5。 x-ref 和 y-ref 需要设置为纸张。这将给出一个很好的注释,例如 plotly legend title

代码:

import plotly.plotly as py
import plotly.graph_objs as go

trace0 = go.Scatter(
x=[1, 2, 3, 4, 5],
y=[1, 2, 3, 4, 5],
)

trace1 = go.Scatter(
x=[1, 2, 3, 4, 5],
y=[5, 4, 3, 2, 1],
)

data = [trace0, trace1]
layout = go.Layout(
legend=dict(
x=0,
y=1,
traceorder='normal',
font=dict(
family='sans-serif',
size=12,
color='#000'
),
bgcolor='#E2E2E2',
bordercolor='#FFFFFF',
borderwidth=2
),
annotations=[
dict(
x=0,
y=1.05,
xref='paper',
yref='paper',
text='Legend Title',
showarrow=False
)
]
)
fig = go.Figure(data=data, layout = layout)

py.iplot(fig)

关于python - plotly 图例标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45555266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com