如何在Dash中并排显示两个图表 [英] How to display two charts side by side in Dash

查看:20
本文介绍了如何在Dash中并排显示两个图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要并排显示的图表,一个是条形图,一个是条形图。这两个图表下面的条形图可能是相同的。我已经尝试了很多,我真的很感激你的帮助。

这是我的代码:

import numpy as np
import pandas as pd
from pandas import read_excel

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 plotly.figure_factory as ff
import plotly.io as pio

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

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

# app = dash.Dash()

external_stylesheets = ['https://codepen.io/amyoshino/pen/jzXypZ.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' : '#FFFFFF',

    'GOLD' : '#EEBC35' ,

    'BROWN' : '#53354D' ,

    'GREEN' : '#42CE90' ,

    'RED' : '#F87861' ,

    'YELLOW' : '#F1F145' ,

    'SKY_BLUE' : '#A3DBE1' ,

    'SILVER': '#CCCCCC' ,

    'LIGHT_BLACK' : '#374649'

    

}

#status options for dropdown

status_options = []

for status in df['Status'].unique():

    status_options.append({'label':str(status),'value':status})

# print(status_options)

#Pie chart static function

def pop_pie():

    pie_data = df.groupby('Status')['Population Census 1991'].count()

    pie_dataframe = pie_data.to_frame().reset_index()

    # print(pie_dataframe)

    # print(df['Status'].unique())

    # print(pie_data.tolist())

    # print(type(pie_data.tolist()))

    # print(pie_data['Status'].tolist())

    # print(pie_data['Population Census 1991'].tolist())

    trace1 = go.Pie(

                labels = pie_dataframe['Status'].tolist(),

                values= pie_dataframe['Population Census 1991'].tolist(),

                textinfo='label+percent',

                name='population 1991 status wise',pull=[0,0,0,0,0,0,0,0,0]

                )

    data = [trace1]

    layout = go.Layout(

            title='piechart',

            )

    fig = go.Figure(data=data)

    return fig

'''

#Barchart static function

def pop_bar():

    trace1 =go.Bar(y=df['Population Census 1991'], 

                        x=df['Name'],name ='1991',

                        marker = {'color' : colors['GREEN']}

                        # orientation='h'

                        )

    trace2 =go.Bar(y=df['Population Census 2001'], 

                        x=df['Name'],name ='2001',

                        marker = {'color' : colors['RED']}

                        # orientation='h'

                        )

    trace3 = go.Bar(y=df['Population Census 2011'], 

                        x=df['Name'],name ='2011',

                        marker = {'color' : colors['YELLOW']}

                        # orientation='h'

                        )

    data = [trace1, trace2, trace3]

    #layout = go.Layout(barmode='group', xaxis={'categoryorder':'array', 'categoryarray':df['District']})

    # layout = go.Layout(barmode='group', xaxis={'categoryorder':'total descending'})

    layout = go.Layout(

    title='Population Census',

    paper_bgcolor=colors['LIGHT_BLACK'],

    plot_bgcolor=colors['LIGHT_BLACK'],

    font ={'color' : colors['WHITE']},

    xaxis_tickfont_size=14,

    yaxis=dict(showgrid=False,

        title='Population',

        titlefont_size=16,

        tickfont_size=14,

    ),

    legend=dict(

        x=0,

        y=1.0,

        bgcolor='rgba(255, 255, 255, 0)',

        bordercolor='rgba(255, 255, 255, 0)',

        orientation="h"

        ),

    barmode='group',

    bargap=0.15, # gap between bars of adjacent location coordinates.

    bargroupgap=0.1, # gap between bars of the same location coordinate.

    xaxis={'categoryorder':'total descending'})

    fig = go.Figure(data=data, layout=layout)

    return fig

'''

app.layout = html.Div(children=[

    html.Div(

            [

        html.H1("Test Dashboard",

        style = {

        

            'textAlign' : 'center',

            'color' : colors['SILVER']

        }

        ),

        html.Div('Developed by Centroxy Solution pvt.ltd',

                style = {

            'textAlign' : 'right',

            'color' : colors['SILVER']

        }

        ),

        html.Img(

        src="https://i.imgur.com/CIxE22f.png",

        className='three columns',

        style={

            'height': '9%',

            'width': '9%',

            'float': 'right',

            'position': 'relative',

            'margin-top': '-91px',

        }),

            html.Br(),

            html.Br()

            ],style={'backgroundColor': colors['LIGHT_BLACK']}

            ),

        html.Div( 

            dcc.Dropdown(id='status_picker',options=status_options,

                          placeholder="Select Status",

                               style = {'color' : colors['LIGHT_BLACK']},

                               multi=True,

                               clearable=True,

                               searchable=True

                            )

                            #,style={"background-color": colors['LIGHT_BLACK']}

                            ,style={'backgroundColor': colors['LIGHT_BLACK']}

        ),  

        html.Div([

            dcc.Graph(id='Bar-Chart')

        ]),

    

        html.Div([

            dcc.Graph(id='pie-chart', figure=pop_pie())

        ]),

            ])

@app.callback(Output('Bar-Chart','figure'),

            [Input('status_picker','value')])

def update_figure(selected_status):

    print(selected_status)

    if selected_status == [] or selected_status == None:

        trace1 =go.Bar(y=df['Population Census 1991'], 

                            x=df['Name'],name ='1991',

                            marker = {'color' : colors['GREEN']}

                            # orientation='h'

                            )

        trace2 =go.Bar(y=df['Population Census 2001'], 

                            x=df['Name'],name ='2001',

                            marker = {'color' : colors['RED']}

                            # orientation='h'

                            )

        trace3 = go.Bar(y=df['Population Census 2011'], 

                            x=df['Name'],name ='2011',

                            marker = {'color' : colors['YELLOW']}

                            # orientation='h'

                            )

    else:

        filtered_df = df[df['Status'].isin(selected_status)]

        print(filtered_df)

        trace1=go.Bar(y=filtered_df['Population Census 1991'], 

                            x=filtered_df['Name'],name ='1991',

                            marker = {'color' : colors['GREEN']}

                            # orientation='h'

                            )

        trace2=go.Bar(y=filtered_df['Population Census 2001'], 

                            x=filtered_df['Name'],name ='2001',

                            marker = {'color' : colors['RED']}

                            # orientation='h'

                            )

        trace3=go.Bar(y=filtered_df['Population Census 2011'], 

                            x=filtered_df['Name'],name ='2011',

                            marker = {'color' : colors['YELLOW']}

                            # orientation='h'

                            )

    traces= [trace1,trace2,trace3]

    '''

    for status in filtered_df['Status'].unique():

        df_by_status = filtered_df[filtered_df['Status'] == selected_status]

        traces.append(

            go.Bar(y=df_by_status['Population Census 1991'], 

                        x=df_by_status['Name'],name ='1991',

                        marker = {'color' : colors['GREEN']}

                        # orientation='h'

                        ))

        traces.append(

            go.Bar(y=df_by_status['Population Census 2001'], 

                        x=df_by_status['Name'],name ='2001',

                        marker = {'color' : colors['RED']}

                        # orientation='h'

                        ))

        traces.append(go.Bar(y=df_by_status['Population Census 2011'], 

                        x=df_by_status['Name'],name ='2011',

                        marker = {'color' : colors['YELLOW']}

                        # orientation='h'

                        ))'''

    return {

        'data' : traces,

        'layout' : go.Layout(

            title='Population Census',

            paper_bgcolor=colors['LIGHT_BLACK'],

            plot_bgcolor=colors['LIGHT_BLACK'],

            font ={'color' : colors['WHITE']},

            xaxis_tickfont_size=14,

            yaxis=dict(showgrid=False,

                title='Population',

                titlefont_size=16,

                tickfont_size=14,

            ),

            legend=dict(

                x=0,

                y=1.0,

                bgcolor='rgba(255, 255, 255, 0)',

                bordercolor='rgba(255, 255, 255, 0)',

                orientation="h"

                ),

            barmode='group',

            bargap=0.15, # gap between bars of adjacent location coordinates.

            bargroupgap=0.1, # gap between bars of the same location coordinate.

            xaxis={'categoryorder':'total descending'})

            }

if __name__ == '__main__':

    app.run_server(port =  '8080' , debug ='True')
此外,背景颜色也不完全是我指定的颜色,请帮助 在下面附加一张图像

推荐答案

您需要使用rowcolumnshtml.Div元素(例如here)。或者,您也可以使用bootstrap元素。

在您的情况下,应该是这样的:

app.layout = html.Div([
    html.Div(
        className="row",
        children=[
            html.Div(
                className="six columns",
                children=[
                    html.Div(
                        children=dcc.Graph(id='left-top-bar-graph')
                    )
                ]
            ),
            html.Div(
                className="six columns",
                children=html.Div(
                    children=dcc.Graph(id='right-top-pie-graph'),
                )
            )
        ]
    ),
    html.Div(
        className="row",
        children=[
            html.Div(
                className="twelve columns",
                children=[
                    html.Div(
                        children=dcc.Graph(id='bottom-bar-graph')
                    )
                ]
            )
        ]
    )
])

这篇关于如何在Dash中并排显示两个图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆