简体   繁体   English

如何在条形图中制作下拉框? (Python/Plotly)

[英]How to make a dropdown box in a bar chart? (Python/Plotly)

Hi everyone I'm comparing the population of different ethnic groups in a bar chart.大家好,我正在比较条形图中不同种族的人口。 I have successfully created my chart but want a drop down menu for the areas.我已经成功创建了我的图表,但想要一个区域的下拉菜单。 bar chart image条形图图像

This is my code, however I am having trouble incourperating the dropdown menu.这是我的代码,但是我无法合并下拉菜单。 Can anyone help?任何人都可以帮忙吗? excel data: excel excel数据: excel


import plotly.graph_objects as go
from plotly.offline import plot
import pandas as pd
import plotly.express as px
import pandas as pd     #(version 1.0.0)
import plotly           #(version 4.5.4) pip install plotly==4.5.4
import plotly.express as px
import dash             #(version 1.9.1) pip install dash==1.9.1
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

raw_data= pd.read_csv('ethnicArea.csv')
data= raw_data[:len(raw_data)-1][['Ethnicity(%)', 'East', 'East Midlands', 'London', 'North East', 'North West', 'South East', 'South West', 'Wales', 'West Midlands', 'Yorkshire and The Humber']]
ethnicArea = list(data.columns)[1:]


fig_data=[]


for i in range(len(data.columns)-1):
    a = ethnicArea[i]
    b = list(data.iloc[:,0])
    c = list(data.iloc[:,i+1])
    print(a)
    print(b)
    print(c)
    fig_data.append(go.Bar(name = a, x = b, y = c))



fig = go.Figure(fig_data)
fig.update_layout(barmode='group', title_text="Black vs White Population By Area (UK)", title_font_family="Times New Roman",title_font_color="black",
                  xaxis_title="Ethnicity group",yaxis_title="Population %",legend_title="Area (UK)", font_size=18)
plot(fig, filename="plot1.html")

app.layout = html.Div([

    html.Div([
        dcc.Graph(id='our_graph')
    ],className='nine columns'),

    html.Div([

        html.Br(),
        html.Div(id='output_data'),
        html.Br(),

        html.Label(['Choose column:'],style={'font-weight': 'bold', "text-align": "center"}),

        dcc.Dropdown(id='my_dropdown',
            options=[
                     {'label': 'East', 'value': 'East'},
                     {'label': 'East Midlands', 'value': 'East Midlands'},
                     {'label': 'London', 'value': 'London'},
                 
 

Since I couldn't read the name of your columns due to you posting an image of your data, I changed the name of your first column to 'Ethnicity'.由于您发布了数据图像,我无法读取您的列名称,因此我将您的第一列的名称更改为“种族”。 Once you make this change, the code will execute and generate a graph from the dropdown menu selection.进行此更改后,代码将执行并从下拉菜单选择中生成图表。

You need to include app.callback and a function for each callback as explained in the documentation.您需要为每个回调包含app.callback和一个函数,如文档中所述


   import plotly.graph_objects as go
   from plotly.offline import plot
   import pandas as pd
   import plotly.express as px
   import pandas as pd  # (version 1.0.0)
   import plotly  # (version 4.5.4) pip install plotly==4.5.4
   import plotly.express as px
   import dash  # (version 1.9.1) pip install dash==1.9.1
   import dash_core_components as dcc
   import dash_html_components as html
   from dash.dependencies import Input, Output
   
   app = dash.Dash(__name__)
   
   rawdata = pd.read_csv('ethnicArea.csv')
   
   ethnicArea = list(rawdata.columns)[1:]
   
   fig_data = []
   
   for i in range(len(rawdata.columns) - 1):
       a = ethnicArea[i]
       b = list(rawdata.iloc[:, 0])
       c = list(rawdata.iloc[:, i + 1])
       print(a)
       print(b)
       print(c)
       fig_data.append(go.Bar(name=a, x=b, y=c))
   
   fig = go.Figure(fig_data)
   fig.update_layout(barmode='group', title_text="Black vs White Population By Area (UK)",
                     title_font_family="Times New Roman", title_font_color="black",
                     xaxis_title="Ethnicity group", yaxis_title="Population %", legend_title="Area (UK)", font_size=18)
   plot(fig, filename="plot1.html")
   
   app.layout = html.Div([
   
       html.Div([
           dcc.Graph(id='our_graph', figure={})
       ], className='nine columns'),
   
       html.Div([
   
           html.Br(),
           html.Div(id='output_data'),
           html.Br(),
   
           html.Label(['Choose column:'], style={'font-weight': 'bold', "text-align": "center"}),
   
           dcc.Dropdown(id='my_dropdown',
                        options=[
                            {'label': val, 'value': val} for val in rawdata.columns.tolist()[1:]],
                        value='East'
                        )])])
   
   @app.callback(
   Output(component_id='our_graph', component_property='figure'),
       Input(component_id='my_dropdown', component_property='value')
   )
   def interactiveGraph(value):
       df = rawdata.copy()
       fig = px.bar(data_frame=df[['Ethnicity',value]], x='Ethnicity', y=value)
       return fig
   
   if __name__ == '__main__':
       app.run_server(debug=True)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM