简体   繁体   English

钻通条形图 Dash plotly

[英]Drill through bar chart Dash plotly

I was trying to create a bar chart where i want to drill through district and then see the population of various cities for 3 year ranges.我试图创建一个条形图,我想在其中钻取区域,然后查看各个城市 3 年范围内的人口。 Basically i found this https://community.plotly.com/t/drill-down-function-for-graphs-embedded-in-dash-app/12290/9 but i am unable to implement基本上我发现了这个https://community.plotly.com/t/drill-down-function-for-graphs-embedded-in-dash-app/12290/9但我无法实现

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Output, Input, State
import numpy as np
import pandas as pd
import plotly.figure_factory as ff
from pandas import read_excel

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# app = dash.Dash()
file_name = 'samplePop1.csv'
df = pd.read_csv(file_name)
print(df.head())

colors = {
    'black' : '#000000',
    'text' :  '#696969',
    'plot_color' : '#C0C0C0',
    'white' : '#FFFFF'
}


app.layout = html.Div ([
                        dcc.Graph(    
                            id = 'bar-chart',
                        figure = { 'data' : 
                                    [
                                        {'x' : df['Name'],'y':df['Population Census 1991'],'type':'bar','name':'Population Census 1991'},
                                        {'x' : df['Name'],'y':df['Population Census 2001'],'type':'bar','name':'Population Census 2001'},
                                        {'x' : df['Name'],'y':df['Population Census 2011'],'type':'bar','name':'Population Census 2011'}

                                    ],
                                'layout' : {
                                    'plot_bgcolor' : colors['white'],
                                    'paper_bgcolor' : colors['white'],
                                    'font' : {
                                        'color' : colors['white']
                                    },
                                    'title' : 'Bar Chart',
                                    'orientation':'h'
                                }
                                }
                        )
                    ])
if __name__ == '__main__':
    app.run_server(port =  '8080' , debug ='True')

the bar chart should show population district wise first for 3 year range and when i click on a district it shall show district wise comparison.条形图应首先显示 3 年范围内的人口区域,当我单击一个区域时,它应显示区域明智的比较。 also another basic chart where their will be 2 click action district wise and city wise to show population for 3 year ranges it should show values clearly more likely it should be scroll-able.还有另一个基本图表,他们将在区域和城市之间单击 2 次,以显示 3 年范围内的人口,它应该更清楚地显示值,它应该是可滚动的。

link to the csv file https://github.com/9192gks/mapbox/blob/master/samplePop1.csv链接到 csv 文件https://github.com/9192gks/mapbox/blob/master/samplePop1.csv

Checkout this example of Drill Down in Dash with the help of callback_context.在 callback_context 的帮助下查看这个在 Dash 中向下钻取的示例。 在此处输入图像描述

In this example I am showcasing just a single level drill down to keep it simple but with few modifications multi -level drill down can be achieved.在这个例子中,我只展示了一个单级向下钻取以保持简单,但只需进行少量修改,就可以实现多级向下钻取。 There's a back button for going back to the original figure.有一个返回按钮可以返回到原始图形。 The back button is shown only on the level two of the drill down and hides on the original bottom level.后退按钮仅在向下钻取的第二层显示并隐藏在原始底层。

Code:代码:

import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

# creating a dummy sales dataframe
product_sales = {'vendors':['VANS','VANS','VANS','VANS','NIKE','NIKE','NIKE','ADIDAS','ADIDAS','CONVERSE','CONVERSE','CONVERSE'],
                 'products': ['Tshirts','Sneakers','Caps','Clothing','Sports Outfit','Sneakers','Caps','Accessories','Bags','Sneakers','Accessories','Tshirts'],
                 'units sold': [2,15,3,8,37,13,7,4,12,7,8,2]
                 }
product_sales_df = pd.DataFrame(product_sales)

# all vendors sales pie chart
def sales_pie():
    df = product_sales_df.groupby('vendors').sum().reset_index()
    fig = px.pie(df, names='vendors',
                 values='units sold', hole=0.4)
    fig.update_layout(template='presentation', title='Sales distribution per Vendor')
    return fig

# creating app layout
app.layout = dbc.Container([
    dbc.Card([
            dbc.Button('🡠', id='back-button', outline=True, size="sm",
                        className='mt-2 ml-2 col-1', style={'display': 'none'}),
            dbc.Row(
                dcc.Graph(
                        id='graph',
                        figure=sales_pie()
                    ), justify='center'
            )
    ], className='mt-3')
])

#Callback
@app.callback(
    Output('graph', 'figure'),
    Output('back-button', 'style'), #to hide/unhide the back button
    Input('graph', 'clickData'),    #for getting the vendor name from graph
    Input('back-button', 'n_clicks')
)
def drilldown(click_data,n_clicks):

    # using callback context to check which input was fired
    ctx = dash.callback_context
    trigger_id = ctx.triggered[0]["prop_id"].split(".")[0]

    if trigger_id == 'graph':

        # get vendor name from clickData
        if click_data is not None:
            vendor = click_data['points'][0]['label']

            if vendor in product_sales_df.vendors.unique():
                # creating df for clicked vendor
                vendor_sales_df = product_sales_df[product_sales_df['vendors'] == vendor]

                # generating product sales bar graph
                fig = px.bar(vendor_sales_df, x='products',
                             y='units sold', color='products')
                fig.update_layout(title='<b>{} product sales<b>'.format(vendor),
                                  showlegend=False, template='presentation')
                return fig, {'display':'block'}     #returning the fig and unhiding the back button

            else:
                return sales_pie(), {'display': 'none'}     #hiding the back button

    else:
        return sales_pie(), {'display':'none'}

if __name__ == '__main__':
    app.run_server(debug=True)

Also check out this thread for more info.另请查看此线程以获取更多信息。

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

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