更新:
如果不定义图例但具有注释定位属性,请使用以下代码。
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)
注意事项:
您需要使用此方法为注释定义x 和y 位置,用于不同的图例。
您可以在text 属性中使用html(例如:text='Legend Title<br>kinda lengthy',)
之前的尝试:
另一种方法是创建图例并使用注释将标题添加到图例中。前提是您不在可编辑模式下使用图表。所以在下面的例子中,图例设置为 x=0 和 y=1,因为我希望我的图例标题高于我的实际图例,所以我将注释位置设置为 x = 0,y = 1.5。 x-ref 和 y-ref 需要设置为纸张。这将给出一个很好的注释,例如
代码:
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)