簡體   English   中英

Python Plotly-多個下拉圖,每個圖都有子圖

[英]Python Plotly - Multiple dropdown plots, each of which have subplots

問題

我正在嘗試結合兩個Python Plotly功能。 其中之一是下拉菜單,用戶可以在其中切換繪圖( 鏈接到示例 )。 另一個功能是子圖。

我的嘗試

我有使用下拉菜單的工作代碼,但沒有子圖。 因此,我在這里查找了如何創建子圖並且我認為我可以使用tools.make_subplots圖,就像處理go.Box圖一樣。 很抱歉,如果這看起來很幼稚,我實際上對Plotly還是很陌生。

但是,這種嘗試根本行不通,我看到了兩個最底層的例外情況。

我的工作代碼(無子圖)

# NOTE: This code goes in between 'START' and 'END' below
traces = []
for data in datas:
    traces.append(go.Box(
                            x=data.index,
                            y=data.values, 
                            showlegend=False
                        ))

我的子圖代碼

import plotly.offline as py
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot, plot
from plotly import tools
init_notebook_mode(connected=True)

### Create individual figures
# START
traces = []
for data in datas:
    fig = tools.make_subplots(rows=1, cols=2)

    trace1 = go.Box(
                    x=data.head(10).index,
                    y=data.head(10).values, 
                    showlegend=False
                )
    trace2 = go.Box(
                    x=data.tail(10).index,
                    y=data.tail(10).values, 
                    showlegend=False
                )   
    fig.append_trace(trace1, 1, 1)
    fig.append_trace(trace2, 1, 2)
    traces.append(fig)
# END

### Create buttons for drop down menu
buttons = []
for i, label in enumerate(labels):
    visibility = [i==j for j in range(len(labels))]
    button = dict(
                 label =  label,
                 method = 'update',
                 args = [{'visible': visibility},
                     {'title': label}])
    buttons.append(button)

updatemenus = list([
    dict(active=-1,
         x=-0.15,
         buttons=buttons
    )
])

layout = dict(title='Title', 
              showlegend=False,
              updatemenus=updatemenus)

fig = dict(data=traces, layout=layout)

iplot(fig, filename='dropdown')

錯誤1

“散布”中不允許使用“布局”

錯誤路徑:['數據'] [0] ['布局']

錯誤2

PlotlyError:參數'figure_or_data'無效。 密謀不會
能夠正確解析生成的JSON。 如果仍要將此“ figure_or_data”發送給Plotly(不推薦),則可以將“ validate = False”設置為繪圖選項。

這就是您看到此錯誤的原因:

“散布”中不允許使用“布局”

...

注意:當我通過validate = False作為繪圖選項時,我看到的只是帶有下拉菜單功能的空白繪圖

Naren是正確的,只需要做出一個子圖即可。 而要創建下拉菜單效果,只需將兩條跡線添加到同一位置即可。

fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 1)

工作代碼

import plotly.offline as py
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot, plot
from plotly import tools
init_notebook_mode(connected=True)

x = [i for i in range(100)]
df_1 = pd.DataFrame([(i, 1+i) for i in range(100)], columns=["X", "Y"])
df_2 = pd.DataFrame([(i, i*i) for i in range(100)], columns=["X", "Y"])
labels = ["Plus one", "Square"]

### Create individual figures
# START
fig = tools.make_subplots(rows=1, cols=2)

trace1 = go.Bar(
                x=df_1.head(10).X,
                y=df_1.head(10).Y, 
                showlegend=False
            )
trace2 = go.Bar(
                x=df_2.head(10).X,
                y=df_2.head(10).Y, 
                showlegend=False
            )

fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 1)

trace1 = go.Bar(
                x=df_1.tail(10).X,
                y=df_1.tail(10).Y, 
                showlegend=False
            )
trace2 = go.Bar(
                x=df_2.tail(10).X,
                y=df_2.tail(10).Y, 
                showlegend=False
            )   
fig.append_trace(trace1, 1, 2)
fig.append_trace(trace2, 1, 2)
# END

### Create buttons for drop down menu
buttons = []
for i, label in enumerate(labels):
    visibility = [i==j for j in range(len(labels))]
    button = dict(
                 label =  label,
                 method = 'update',
                 args = [{'visible': visibility},
                     {'title': label}])
    buttons.append(button)

updatemenus = list([
    dict(active=-1,
         x=-0.15,
         buttons=buttons
    )
])

fig['layout']['title'] = 'Title'
fig['layout']['showlegend'] = False
fig['layout']['updatemenus'] = updatemenus

iplot(fig, filename='dropdown')

謝謝

非常感謝Naren Murali的幫助! 稍微編輯一下代碼就給了我答案。

我一直想創造這個。 在此處輸入圖片說明 在此處輸入圖片說明

但是您的代碼給了我這些圖... 在此處輸入圖片說明 在此處輸入圖片說明

我認為您make_subplots()圖的概念有誤解,得到錯誤的原因是因為make_subplots()函數將創建其自己的layout對象,因此您將得到錯誤。

'layout' is not allowed in 'scatter'

Path To Error: ['data'][0]['layout']

修改子圖布局的正確方法是創建子圖並訪問各個對象屬性並進行設置,如下所示。

updatemenus = list([
    dict(active=-1,
         x=-0.15,
         buttons=buttons
    )
])

fig['layout']['title'] = 'Title'
fig['layout']['showlegend'] = False
fig['layout']['updatemenus'] = updatemenus

另外,每次運行for循環時,您都在創建一個新的子圖對象,這是錯誤的 我說的是下一行。

traces = []
for data in datas:
    fig = tools.make_subplots(rows=1, cols=2)

您只需要分配一次,請參考以下工作示例,並嘗試對用例實施相同的方法。

import plotly.offline as py
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot, plot
from plotly import tools
init_notebook_mode(connected=True)
df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"])
labels = ["A", "B"]
datas = [df, df]
### Create individual figures
# START
fig = tools.make_subplots(rows=2, cols=2)

for i, data in enumerate(datas):

    trace1 = go.Bar(
                    x=data.head(10).A,
                    y=data.head(10).B, 
                    showlegend=False
                )
    trace2 = go.Bar(
                    x=data.tail(10).A,
                    y=data.tail(10).B, 
                    showlegend=False
                )   
    fig.append_trace(trace1, i + 1, 1)
    fig.append_trace(trace2, i + 1, 2)

### Create buttons for drop down menu
buttons = []
for i, label in enumerate(labels):
    visibility = [i==j for j in range(len(labels))]
    button = dict(
                 label =  label,
                 method = 'update',
                 args = [{'visible': visibility},
                     {'title': label}])
    buttons.append(button)

updatemenus = list([
    dict(active=-1,
         x=-0.15,
         buttons=buttons
    )
])

fig['layout']['title'] = 'Title'
fig['layout']['showlegend'] = False
fig['layout']['updatemenus'] = updatemenus

iplot(fig, filename='dropdown')

請告訴我是否可以解決您的問題!

暫無
暫無

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

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