在 plotly 中用下拉菜单绘制两个数据集

Plot two dataset with dropdown menu in plotly

我试图在同一个数字上显示两个随每个国家/地区更新的数据集:一个是美国进口数据,另一个是美国出口数据。这是我正在使用的数据 https://www.kaggle.com/khushishahh/global-patterns-of-us-merchandise-trade,我能够创建两个图表,但图表更新不正确。 有人可以帮帮我吗。 提前致谢。

这是我试过的:

temp_imp = temp_imp.melt(id_vars=['Partner'], 
                         var_name="Year", 
                         value_name="Value")

temp_exp = temp_exp.melt(id_vars=['Partner'], 
                       var_name="Year", 
                       value_name="Value")


trace0 =(
    (
       px.line(
           data_frame = temp_imp[temp_imp['Partner']==temp_imp['Partner'].head(1).squeeze()]
          ,x='Year'
          ,y='Value')  
).data[0]
)

trace1 =(
    (
       px.line(
           data_frame = temp_exp[temp_exp['Partner']==temp_exp['Partner'].head(1).squeeze()]
          ,x='Year'
          ,y='Value')  
).data[0]
)

                            
buttons = []
for country in temp_imp['Partner'].sort_values().unique():
    imp_c = temp_imp[temp_imp['Partner']==country]
    args_x=[imp_c['Year']]
    args_y=[imp_c['Value']]
    args_f=[0]
    imp_e = temp_exp[temp_exp['Partner'] == country]
    args_y.append(imp_e['Value'])
    args_f.append([0])

    buttons.append(dict(method='restyle',
                        label=country,
                        visible=True,
                        args=[{'x': args_x,'y':args_y}, args_f]
                    )
                  )
    
updatemenu=[dict(
                   buttons=buttons
                  ,direction='down'
                  ,pad={'r': 10, 't': 10}
                  ,showactive=True
                  ,x=-0.05
                  ,xanchor='left'
                  ,y=1.1
                  ,yanchor='top')] 


fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(trace0)
fig.add_trace(trace1,secondary_y=True)
                            
fig.data[0].line.dash='dash'
fig.data[0].mode ='markers+lines' 
fig.data[0].line.color='#00CC96' 
fig.update_layout(font_size=10)


fig.update_traces(showlegend=True, selector=dict(type='histogram'))
fig.update_layout( updatemenus=updatemenu
                  ,height=600
                  ,barmode='overlay'
                  ,margin=dict(r=10, t=20, b=30, l=0)
                  ,legend=dict(
                               orientation='h'
                              ,yanchor='top'
                              ,y=0.33
                              ,xanchor='left'
                              ,x=-0.05
                            ))
gc.collect()
fig.show()
  • 已对此进行调查并得出结论,通过可见性进行管理比在跟踪中更改数据更简单
  • 自动从 kaggle 下载数据
  • 使用 Plotly Express 设置线条和标记样式以及可见性
  • 生成轨迹
  • 然后构建 updatemenus 作为 list / dict comprehensions
  • 使用 namelegendgroup 是微妙的,以允许在 legend
  • 中使用有意义的标签
import kaggle.cli
import sys, math
import pandas as pd
from pathlib import Path
from zipfile import ZipFile
import plotly.express as px

# download data set
# https://www.kaggle.com/khushishahh/global-patterns-of-us-merchandise-trade
sys.argv = [
    sys.argv[0]
] + "datasets download khushishahh/global-patterns-of-us-merchandise-trade".split(" ")
kaggle.cli.main()

# open downloaded zip file and create a dict of data frames
zfile = ZipFile("global-patterns-of-us-merchandise-trade.zip")
dfs = {f.filename: pd.read_csv(zfile.open(f)) for f in zfile.infolist()}

# structures dataframes for use with plotly
exp = dfs["data_exports_of_naics_total_all_merchandise.csv"].melt(
    id_vars=["Partner"], var_name="Year", value_name="Value"
)
imp = dfs["data_imports_of_naics_total_all_merchandise.csv"].melt(
    id_vars=["Partner"], var_name="Year", value_name="Value"
)


fig = (
    px.line(exp, x="Year", y="Value", color="Partner")
    .update_traces(
        line={"color": "#00CC96", "dash": "dash"},
        mode="lines+markers",
        visible=False,
        name="Export",
    )
    .update_traces(visible=True, selector={"legendgroup": "World"})
    .add_traces(
        px.line(imp, x="Year", y="Value", color="Partner")
        .update_traces(line={"color": "blue"}, visible=False, name="Import")
        .update_traces(visible=True, selector={"legendgroup": "World"})
        .data
    )
)

fig.update_layout(
    updatemenus=[
        {
            "buttons": [
                {
                    "label": p,
                    "method": "update",
                    "args": [{"visible": [t["legendgroup"] == p for t in fig.data]}],
                }
                for p in imp["Partner"].unique()
            ]
        }
    ]
)

fig.show()