如何在 Python 中使用 Plotly 创建的绘图中添加按钮或下拉列表?

问题描述

我是 Plotly 的新手,对它的交互功能很着迷.我有三个国家发电组合的三个熊猫数据框,如下所示:

I am new to Plotly and fascinated by its interactive features. I have three pandas dataframes of electricity generation mix of three countries, which looks like this:

我已经能够使用 Plotly 创建一个交互式条形图,用于基于 df1 使用的发电组合

I have been able to create an interactive bar chart using Plotly for electricity generation mix based on df1 using

将 plotly.express 导入为 pxfig=px.bar(df1, title=TWh (2000-2019)德国发电量组合", color_discrete_sequence=colors)图

import plotly.express as px fig=px.bar(df1, title="Electricity generation mix of Germany in TWh (2000-2019)", color_discrete_sequence=colors) fig

我打算在此条形图中添加一个按钮或下拉菜单,我可以在其中根据每个数据框(df1、df2 和 df3)选择国家/地区.最好的方法是什么?我是否应该将所有三个国家的数据都放在一个数据框中?

I intend to add a button or dropdown to this bar chart, where I can select countries based on each data frame (df1,df2 and df3). What would be the best approach to do it? Should I rather have the data of all three countries in one dataframe?


解决方案

最简单的方法是使用图形对象库并使用add_trace"遍历您的数据.Plotly 图的方法.

The easiest way to do this is to use the graph objects library and iterate through your data with the "add_trace" method of a Plotly figure.

import pandas as pd
import plotly.graph_objects as go

#Dummy data
df_germany = pd.DataFrame({'Fuels':[2010,2011],'Coal':[200,250],'Gas':[400,500]})
df_poland = pd.DataFrame({'Fuels':[2010,2011],'Coal':[500,150],'Gas':[600,100]})
df_spain = pd.DataFrame({'Fuels':[2010,2011],'Coal':[700,260],'Gas':[900,400]})

#put dataframes into object for easy access:
df_dict = {'Germany': df_germany, 
           'Poland': df_poland, 
           'Spain': df_spain}

#create a figure from the graph objects (not plotly express) library
fig = go.Figure()

buttons = []
i = 0

#iterate through dataframes in dict
for country, df in df_dict.items():
    #iterate through columns in dataframe (not including the year column)
    for column in df.drop(columns=['Fuels']):
        #add a bar trace to the figure for the country we are on
        fig.add_trace(go.Bar(
                          name = column,
                          #x axis is "fuels" where dates are stored as per example
                          x = df.Fuels.to_list(),
                          #y axis is the data for the column we are on
                          y = df[column].to_list(),
                          #setting only the first country to be visible as default
                          visible = (i==0)
                        )
                     )
        
    #args is a list of booleans that tells the buttons which trace to show on click
    args = [False] * len(df_dict)
    args[i] = True
    
    #create a button object for the country we are on
    button = dict(label = country,
                  method = "update",
                  args=[{"visible": args}])
    
    #add the button to our list of buttons
    buttons.append(button)
    
    #i is an iterable used to tell our "args" list which value to set to True
    i+=1
        
fig.update_layout(
    updatemenus=[
        dict(
        #change this to "buttons" for individual buttons
        type="dropdown",
        #this can be "left" or "right" as you like
        direction="down",
        #(1,1) refers to the top right corner of the plot
        x = 1,
        y = 1,
        #the list of buttons we created earlier
        buttons = buttons)
    ],
    #stacked bar chart specified here
    barmode = "stack",
    #so the x axis increments once per year
    xaxis = dict(dtick = 1))

fig.show()
        

应该让步:

相关文章