情节:如何使用updatemenus更新具有多个相关迹线的图形?

问题描述 投票:1回答:1

我正在使用将要更新的字段作为参数的updatemenus更新散点图:

dict(label = category,
      method = 'update',
      args = [dict(x=[df[(df['cat_name'] == category) & (df['cat_level'] == cat_level)]['value']], 
                        y=[df[(df['cat_name'] == category) & (df['cat_level'] == cat_level)]['count']],
                        meta = [["Category:" + category]]
                                          )])

我有第二条要添加的迹线(这是最合适的行),我希望随着菜单选项的更改进行更新(当用户选择菜单类别时,该类别数据的视觉更新-因此,最适合的行应更改)。

是否有聪明的方法来构造它?

python plot plotly visualization
1个回答
0
投票

如果您的数据是熊猫数据框,那么这里的关键是为其自身数据框中的每一列构建一个线性模型,然后使用像这样的循环为每个源列和关联的线性模型添加一个带菜单的下拉菜单:] >

for col in df.columns:
    buttons.append(dict(method='restyle',
                        label=col,
                        visible=True,
                        args=[{'y':[df[col], df_reg[col+'_model']],
                               'x':[df.index],
                               'type':'scatter'}],
                        )
                  )

图1:

列A和相关的线性模型:

enter image description here

图2:

B列和相关的线性模型:

enter image description here

带有可复制数据示例的完整代码:

# imports
import plotly.graph_objs as go
import numpy as np
import pandas as pd
import plotly.express as px
from datetime import datetime
# conda install -c anaconda scikit-learn
from sklearn.linear_model import LinearRegression #(conda install -c anaconda scikit-learn)

# data sample
nperiods=200
np.random.seed(123)
df = pd.DataFrame(np.random.randint(-10,12,size=(nperiods, 4)), columns=list('ABCD'))
datelist = pd.date_range(datetime(2020, 1, 1).strftime('%Y-%m-%d'), periods=nperiods).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df.iloc[0]=0
df=df.cumsum()

# build dataframe df_reg with linear models using sklearn
# for each column in df
df_reg = pd.DataFrame()
# regression
for col in df:
    #print(col)
    reg = LinearRegression().fit(np.vstack(np.arange(0, len(df))), df[col].values)
    df_reg[col+'_model'] = reg.predict(np.vstack(np.arange(0, len(df))))


#plotly
fig=go.Figure()

# set up one trace for source data in df
# and one trace for each linear model in df_reg
fig.add_trace(go.Scatter(x=df.index,
                             y=df[df.columns[0]],
                             visible=True))

fig.add_trace(go.Scatter(x=df.index,
                             y=df_reg[df_reg.columns[0]],
                             visible=True))
# Define updatemenus
updatemenu=[]
buttons=[]

# add buttons to select column in df
# and the associated linear model in df_reg
for col in df.columns:
    buttons.append(dict(method='restyle',
                        label=col,
                        visible=True,
                        args=[{'y':[df[col], df_reg[col+'_model']],
                               'x':[df.index],
                               'type':'scatter'}],
                        )
                  )

# some adjustments to the updatemenus
updatemenu=[]
your_menu=dict()
updatemenu.append(your_menu)

updatemenu[0]['buttons']=buttons
updatemenu[0]['direction']='down'
updatemenu[0]['showactive']=True

# add dropdown menus to the figure
fig.update_layout(showlegend=False, updatemenus=updatemenu)
fig.show()
© www.soinside.com 2019 - 2024. All rights reserved.