python - Python:在 Plotly 的子图中共享图例
问题描述
我正在尝试用两个子图绘制一个图,但是我得到了具有相同名称的单独图例。
import plotly as py
import plotly.graph_objs as go
trace0 = go.Scatter(
x=[1, 2, 3, 4, 5],
y=[1, 2, 3, 4, 5],
xaxis='x1', yaxis='y1',
name='legend'
)
trace1 = go.Scatter(
x=[1, 2, 3, 4, 5],
y=[5, 4, 3, 2, 1],
xaxis='x2', yaxis='y2',
name='legend'
)
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
)
]
)
layout = go.Layout(
xaxis1=dict(
domain=[0, 0.45],
),
yaxis1=dict(
domain=[0.75, 1],
),
yaxis2=dict(
domain=[0.75, 1],
anchor="x2"
),
xaxis2=dict(
domain=[0.55, 1],
showticklabels=False
)
)
fig = go.Figure(data=data, layout = layout)
iplot(fig)
我在期待什么?
两个情节都有一个共同的传说。当我悬停/单击图例时,我应该能够隔离痕迹(应该隔离所有常见的图例)
如果我单击 fig1 中的“legend”,则 fig2 中的“legend”也应该被隔离,因为它们共享共同的图例。
好心劝告。
解决方案
听起来您想通过单个图例项控制相关跟踪。如果我理解正确,请看下面。
需要注意的关键属性是:legendgroup
和showlegend
。这是Plotly 关于该主题的文档的链接。
示例代码:
import numpy as np
from plotly.offline import iplot
# Creating a dataset.
x = np.linspace(0, np.pi*2, 250)
y1 = [np.sin(i) for i in x]
y2 = [np.cos(i) for i in x]
y3 = [np.sin(i) for i in x**2]
y4 = [np.cos(i) for i in x**2]
# Plot the data with grouped legends.
data = []
layout = {}
data.append({'x': x, 'y': y1, 'name': 'sin', 'legendgroup': 'sin'})
data.append({'x': x, 'y': y2, 'name': 'cos', 'legendgroup': 'cos'})
data.append({'x': x, 'y': y3, 'yaxis': 'y2', 'name': 'sin', 'legendgroup': 'sin', 'showlegend': False})
data.append({'x': x, 'y': y4, 'yaxis': 'y2', 'name': 'cos', 'legendgroup': 'cos', 'showlegend': False})
layout['xaxis1'] = {'domain': [0.00, 1.00], 'anchor': 'y2'}
layout['yaxis1'] = {'domain': [0.55, 1.00]}
layout['yaxis2'] = {'domain': [0.00, 0.45]}
iplot({'data': data, 'layout': layout})
输出:
请注意,在图 1 中,两个图中都显示了 sin 和 cos 轨迹。然后,在图 2 中,我使用单个图例项关闭了两个图中的 cos 跟踪。
图1:
图 2:
推荐阅读
- c# - 如何继续 WaterfallStep 而不是调用 Dispatcher
- java - 关于 cql 过滤器
- python - Selenium Python - GetAttr
- java - 如何将光标位置设置到 EditText 的末尾?
- java - 带有依赖注入的 Spring Boot 和 Jersey 过滤器
- php - 将序列化字符串转换为对象或数组
- javascript - Kuzzle getUser by JWT Token 早期生成
- feathersjs - 使用 FeatherJS 和 Joi 进行独特的字段验证
- angular - 基于使用 ng-bootstrap Angular 8 的选择来显示/隐藏的下拉选择
- java - java中的ArrayList不删除-1