【问题标题】:How can I add a button or dropdown in a plot created using Plotly in Python? [duplicate]如何在 Python 中使用 Plotly 创建的绘图中添加按钮或下拉菜单? [复制]
【发布时间】:2021-01-13 21:55:01
【问题描述】:

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

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

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

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

【问题讨论】:

  • 查看我的两篇文章(onetwo)以获得一些一般性的指导。如果您仍然遇到困难,非常欢迎您就您的具体情况向我寻求帮助

标签: python python-3.x button drop-down-menu plotly


【解决方案1】:

最简单的方法是使用图形对象库并使用 Plotly 图形的“add_trace”方法遍历数据。

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()
        

应该让步:

【讨论】:

  • 您能否指定我如何定义颜色序列,例如煤用黑色,天然气用灰色?
  • @HimalayaBirShrestha 关于你的评论,你昨天不是问了一个非常相似的问题吗?
  • @vestland 是的,我做到了。但情况不同,因为 plotly.express 与 plotly.graph_objects 不同。我尝试遍历 fig.add_trace(go.Bar(marker_color=color) 中的颜色。我能够为第一个选项获得所需的颜色,但是一旦我从下拉列表或按钮中选择了第二个或第三个选项,颜色被扭曲了。因此,我想问一下在这种情况下定义颜色序列的合适方法是什么。
  • 将“marker = dict(color = ["我们所在列的颜色"] * len(df.Fuels.to_list())”添加到“Bar”对象内的for循环中
猜你喜欢
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2021-03-13
  • 2021-11-04
  • 2021-01-13
  • 1970-01-01
相关资源
最近更新 更多