簡體   English   中英

Python:在 Plotly 的子圖中共享圖例

[英]Python: Share legend among subplots in 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”也應該被隔離,因為它們共享共同的圖例。

友善的建議。

聽起來您想通過單個圖例項控制相關跟蹤。 如果我理解正確,請看下面。

要注意的關鍵屬性是: legendgroupshowlegend 這是有關該主題的 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:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM