Exemple #1
0
def render_content(tab):
    if tab == 'tab-1':
        return html.Div([
            dac.TabItem(id='content_value_boxes',
                        children=[
                            html.Div([
                                dac.InfoBox(title="TOTAL CONFIRMED ",
                                            value=sum(report["Confirmed"]),
                                            gradient_color="danger",
                                            icon="bookmark"),
                                dac.InfoBox(title="TOTAL RECOVERED",
                                            gradient_color="success",
                                            value=sum(Recovered.iloc[:, -1]),
                                            icon="bookmark"),
                                dac.InfoBox(title="TOTAL DEATHS",
                                            color="black",
                                            value=sum(report["Deaths"]),
                                            icon="bookmark")
                            ],
                                     className='row')
                        ]),
            dbc.Container([
                dcc.RadioItems(
                    id='maptype',
                    options=[{
                        'label': i,
                        'value': i
                    } for i in [
                        'National_map', 'open-street-map', 'stamen-toner', '3D'
                    ]],
                    value='National_map',
                    labelStyle=items_style),
            ]),
            dcc.Graph(id='graph-1-tabs', figure=fig)
        ])
    elif tab == 'tab-2':
        return html.Div([
            html.H3('Worldwide Evolution of COVID19'),
            dcc.Graph(id='graph-2-tabs', figure=fig3),
            html.H2('Evolution of COVID19 by country'),
            dcc.Dropdown(id='country',
                         options=[{
                             'label': i,
                             'value': i
                         } for i in factors],
                         value=['Spain', 'Italy'],
                         multi=True),
            html.Div([
                html.Div([dcc.Graph(id='confirmed-evolution')],
                         className="six columns",
                         style={'display': 'inline-block'}),
                html.Div([dcc.Graph(id='death-evolution')],
                         className="six columns",
                         style={'display': 'inline-block'}),
            ],
                     className="row",
                     style={
                         'width': '100%',
                         'display': 'inline-block'
                     })
        ])
    elif tab == 'tab-3':
        return html.Div([
            dash_table.DataTable(
                id='datatable-interactivity',
                columns=[{
                    "name": i,
                    "id": i,
                    "deletable": True,
                    "selectable": True
                } for i in globalreport.columns],
                data=globalreport.to_dict('records'),
                editable=True,
                filter_action="native",
                sort_action="native",
                sort_mode="multi",
                column_selectable="single",
                row_selectable="multi",
                row_deletable=True,
                selected_columns=[],
                selected_rows=[],
                page_action="native",
                page_current=0,
                page_size=10,
                style_table={'textAlign': 'center'},
                style_cell={
                    'padding': '5px',
                    'fontSize': 12,
                    'textAlign': 'center'
                },
                style_header={
                    'backgroundColor': 'white',
                    'fontWeight': 'bold',
                    'fontSize': 12
                },
            )
        ])
country_name_list = choropleth_country_map_helpers.get_property_items_list(
    country_map_available_property_items, country_map_name_mapper_dict,
    country_map_property)

layout = html.Div([
    html.Div(firstrow_layout,
             className='row',
             style={
                 'margin-top': 20,
                 'margin-bottom': 20
             }),
    html.Div(secondrow_layout, className='row', style={'margin-bottom': 20}),
    html.Div(
        dcc.Graph(id='choropleth-country-map',
                  config={'displayModeBar': False},
                  style={'margin-bottom': 8},
                  hoverData={'points': [{
                      'customdata': 'Indonesia'
                  }]}),
        className='row',
    ),
    html.Div([
        dcc.Graph(id='summary-heatmap',
                  style={'margin-bottom': 8},
                  className='six columns',
                  hoverData={
                      'points': [{
                          'x': '2019-08-26 -',
                          'y': 'CPO Product Price'
                      }]
                  },
                  config={'displayModeBar': False}),
app.layout = html.Div(children=[

    # append the visualization to the page
    dcc.Graph(
        id='example-graph',
        figure={
            # configure the data
            'data': [
                go.Scatter(
                # setting x as fat, and y as calories (points represent data)
                    x= df['fat'], 
                    y = df['calories'], 
                mode = 'markers',
                text = df ['name'],
                marker = {
                    'size': 12,
                    'color': 'rgb(0,255,0)'
                }
            ) 
        ],
            # configure the layout of the visualization --
            # set the title 
            'layout': {
                'title': 'Fat vs. Calories',
                'xaxis': {'title': 'Fat (g)'},
                'yaxis': {'title': 'Calories'}
            }
        }
    )
])

if __name__ == '__exercise3__':
     dcc.Dropdown(
         id='currency',
         options=[{'label': 'EUR/USD', 'value': 'eur_usd'}, {'label': 'BTC/USD', 'value': 'btc_usd'}],
         value='eur_usd',
         placeholder="Currency",
         style={'width': '100%', 'display': 'inline-block'}
     ),
 ], style={'width': '100%', 'display': 'inline-block'}),
 html.Br(),
 html.Br(),
 dcc.Tabs(id="tabs", children=[
     dcc.Tab(label='Recurrent Neural Network ', value='rnn', selected_style={'backgroundColor': '#21252C', 'color': 'white'}),
     dcc.Tab(label='Convolutional neural network', value='cnn', selected_style={'backgroundColor': '#21252C', 'color': 'white'}),
 ], value="rnn", colors={'border': 'gray', 'background': '#21252C'}),
 html.Div([
     dcc.Graph(id='graph'),
 ], className='twelve columns eur-usd-graph'),
 html.Div([
     dcc.Dropdown(id='type', options=[
         {"label": "Line", "value": "line_trace"},
         {"label": "Mountain", "value": "area_trace"},
         {
             "label": "Colored bar",
             "value": "colored_bar_trace",
         },
     ], value="line_trace", clearable=False, style={'width': '98%'}),
 ], className='twelve columns', style={'display': 'inline-block', 'width': '40%'}),
 html.Div([
     dcc.Dropdown(id='metric', options=[
         {
             "label": "Accumulation/D",
                      value=dt.date.today()),
            dcc.Input(id='enddate_input', type='Date', value=dt.date.today()),
        ]),
    ],
             style={
                 'width': 200,
                 'height': 200
             }),
    html.Button(id='submit_button',
                n_clicks=0,
                children='Submit',
                style={
                    'fontSize': 20,
                    'height': 50
                }),
    dcc.Graph(id='feature-graphic'),
    dcc.Markdown(id='content_text', containerProps={'fontSize': 200}),
])


# 어떤 DB인지에 따라 능동적으로 Dropdown 변경해줄 수 있는 코드 (현재는 하나의 DB라서 의미 없는 코드)
@app.callback(Output('company_type', 'options'),
              [Input('column_type', 'value')])
def set_company_type(select_column):
    return [{'label': i, 'value': i} for i in all_options[select_column]]


@app.callback(Output('company_type', 'value'),
              [Input('company_type', 'options')])
def set_company_value(avail_options):
    return avail_options[0]['value']
Exemple #6
0
              '101-004-7108173-009',]

app.layout = html.Div(children=[
    html.H1(children='MLinc Thunder Dashboard'),

    html.Div(children='''
        Making billions and billions and billions.
    '''),

    dcc.Dropdown(
        id='dropdown',
        options=[{'label': i, 'value': i} for i in account_id],
        value=account_id[0]
    ),

    dcc.Graph(id='ML_dashboard', style={'height': '90vh'}),

    html.H2(children='Mede mogelijk gemaakt door:'),

    html.Img(src='data:image/png;base64,{}'.format(encoded_image.decode()))
    ])


@app.callback(
    dash.dependencies.Output('ML_dashboard', 'figure'),
    [dash.dependencies.Input('dropdown', 'value')])

def update_figure(selected_account):
    conf_input = from_conf_file('all', r'C:\Data\2_Personal\Python_Projects\MLinc\mlinc\conf.ini')
    conf_input['accountid'] = selected_account
Exemple #7
0
 html.H1(children='Welcome to a DataViz Project using DASH',
         style={
             'color': 'blue',
             'fontSize': 48
         }),
 html.
 H3(children='Created by: Kunal PATIL (AIS) and Salil MARATH-PONMADOM (DSA)',
    style={
        'color': 'grey',
        'fontSize': 20
    }),
 html.Div(children='''
     Magnitude of Earthquakes in Japan during 2001-2018 
 '''),
 dcc.Graph(
     id='JE1',
     figure=fig_scatter_mapbox,
 ),
 html.
 H6(children=
    "Observation and Comments: Using Scatter Mapbox, We can observe geaographical distribution of Earthquake's origin."
    "All the earthquakes originated from east side in pacific ocean.",
    style={
        'color': 'black',
        'fontSize': 12
    }),
 dcc.Graph(id='JE2', figure=fig_line),
 html.
 H6(children=
    "Observation and Comments: As observed from scatter mapbox, we know the count is highest during 2011-12. "
    "With Line graph, we can see the highest magnitude of earthquake observed in March 2011 (9.1)",
    style={
Exemple #8
0
        for json_entry in ['', '']
    ]),

    html.Div(children=str(str(int(round(avgdelaynumber * 100))) + '% of S-Bahns delayed in total on this line. '),
             style={
                 # 'textAlign': 'center',
                 # 'color': colors['text']

             }),

    html.Div(children=str(str(((avgdelay))) + ' minutes average delay on this line.'), style={
        # 'textAlign': 'center',
        # 'color': colors['text']

    }),
    dcc.Graph(id='graph'),

])


@app.callback(
    dash.dependencies.Output('graph', 'figure'),
    [dash.dependencies.Input('dropdown', 'value')])
def update_figure(value):
    dff = df[df['Endstation'].eq(value)]

    # Set order for stations
    if value == 'Flughafen München':
        order = ['Herrsching', 'Seefeld-Hechendorf', 'Steinebach', 'Weßling', 'Neugilching', 'Gilching-Argelsried',
                 'Geisenbrunn',
                 'Germering-Unterpfaffenhofen', 'Harthaus', 'Freiham', 'Neuaubing',
Exemple #9
0
#df2 = pd.DataFrame({'percentage': df.groupby(['company'] ,as_index=False).size() / len(df) }).reset_index()

#df2 = pd.DataFrame({'percentage': df.groupby([ 'site']).size() / len(df)}).reset_index()
#df2 = df.groupby('zone').count().reset_index()
#print(df2.head())

app = dash.Dash()

app.layout = html.Div([
    dcc.Graph(id='scatterplot',
              figure={
                  'data': [
                      go.Box(y=df[df.site == 'pisoscom']['price'],
                             name="pisos.com"),
                      go.Box(y=df[df.site == 'habitaclia']['price'],
                             name="habitaclia")
                  ],
                  'layout':
                  go.Layout(title='Price/Surface',
                            xaxis={'title': 'price distribution'},
                            yaxis={'title': 'surface'})
              })
])
"""
app.layout = html.Div([dcc.Graph(id='scatterplot', 
                    figure = {'data': [
                        go.Box(
                            y=df[df.site=='pisoscom']['price'],
                            name="pisos.com"
                            
                            
Exemple #10
0
                options=[{'label': i, 'value': i} for i in available_indicators],
                value=available_indicators[0]
            )],
                style={'width': '50%', 'display': 'inline-block'})],
                   
               style={
                 #'borderBottom': 'thin lightgrey solid',
                 'backgroundColor': 'rgb(255,255,255)',
                 #'padding': '10px',
                 #'width': '100%',
                 #'margin': '20px, 10px, 30px, 40px',
                 #'font-family': 'Century Gothic'
                 }),
    
    dcc.Graph(
        id='graph',
        style={'height': 600}
    )
],
                 style={'font-family': 'Century Gothic',
                        'margin': '5px'
        })


#1
@app.callback(
     Output(component_id='result', component_property='children'),
    [Input(component_id='tc', component_property='value'),
     Input(component_id='rt', component_property='value')])
def update_three_inputs(tc, rt):
    if tc is not None and tc is not '' and rt is not None and rt is not '':
        try:
#     routes_pathname_prefix='/dash3/'
# )

conn = sqlite3.connect("hospital_data.db")
df = pd.read_sql_query("SELECT * FROM data", conn)

x1_list = ["masks", "ventilators", "faceshields", "gowns"]
y1_list = [df[key].sum() for key in x1_list]
app1.layout = html.Div(
    [
        dcc.Graph(
            id='graph',
            figure={
                'data': [
                    {'x': x1_list,
                     'y': y1_list, 'type': 'bar', 'name': 'Supplies'},
                ],
                'layout': {
                    'title': 'Supplies Requested by Hospitals'
                }
            }
        ),
    ]
)

@server.route("/")
def root():
    return render_template("index.html")


@server.route("/about")
def about():
Exemple #12
0

app.layout = html.Div(children=[
    html.H1(children="Private Dash App"),
    html.Div(id='placeholder', style={'display': 'none'}),
    html.Div(id='welcome'),
    dcc.Graph(id='example-graph',
              figure={
                  'data': [
                      {
                          'x': [1, 2, 3],
                          'y': [4, 1, 2],
                          'type': 'bar',
                          'name': 'SF'
                      },
                      {
                          'x': [1, 2, 3],
                          'y': [2, 4, 6],
                          'type': 'bar',
                          'name': 'Montreal'
                      },
                  ],
                  'layout': {
                      'title': 'Dash Data Visualization'
                  }
              })
])


@app.callback(Output('welcome', 'children'), [Input('placeholder', 'value')])
def on_load(value):
    return "Welcome, {}!".format(session['email'])
Exemple #13
0
                                           },
                                           0.35: {
                                               'label': '0.35'
                                           },
                                           0.4: {
                                               'label': '0.4'
                                           },
                                           0.45: {
                                               'label': '0.45'
                                           },
                                           0.5: {
                                               'label': '0.5'
                                           }
                                       }),
                            html.Hr(),
                            dcc.Graph(id='plot_ts'),

                            #  Temporary hack for live dataframe caching
                            #  'hidden' set to 'loaded' triggers next callback
                            html.P(hidden='unload',
                                   id='raw_container',
                                   style={'display': 'none'}),
                            html.P(hidden='unload',
                                   id='filtered_container',
                                   style={'display': 'none'})
                        ])
                    ]),
                dcc.Tab(label='tab_2')
                #dcc.Tab(label='tab_3'),
                #dcc.Tab(label='tab_4'),
                #dcc.Tab(label='tab_5')
Exemple #14
0
         'display': 'inline-block',
         'vertical-align': 'top',
         'min-height': '355px',
         'position': 'relative',
         "box-shadow":
         "0 4px 8px 0 rgba(0, 0, 0, 0.05), 0 6px 20px 0 rgba(0, 0, 0, 0.05)",
         "font-family": "Helvetica"
     },
 ),
 html.Div(
     [
         html.Div([
             dcc.Graph(id="map_graph",
                       config={
                           'modeBarButtonsToRemove':
                           ['select2d', 'lasso2d'],
                           'displaylogo':
                           False
                       })
         ],
                  id="map_container",
                  className="map_container",
                  style={'margin-top': '20px'}),
     ],
     id="map_area",
     className="map area",
     style={
         "margin":
         "5px",
         "width":
         "58%",
Exemple #15
0
                            ),
                        ],
                    ),
                    html.P(id="total-rides"),
                    html.P(id="total-rides-selection"),
                    html.P(id="date-value"),
                    dcc.Markdown(children=[
                        "Source: [Los Angeles Police Department](https://catalog.data.gov/dataset/crime-data-from-2010-to-present-c7a76)"
                    ]),
                ],
            ),
            # Column for app graphs and plots
            html.Div(
                className="eight columns div-for-charts bg-grey",
                children=[
                    dcc.Graph(id="map-graph"),
                    html.Div(
                        className="text-padding",
                        children=["Hourly Crime Totals On Selected Date"],
                    ),
                    dcc.Graph(id="histogram"),
                ],
            ),
        ],
    )
])

# Gets the amount of days in the specified month
# Index represents month (0 is April, 1 is May, ... etc.)
daysInMonth = [30, 31, 30, 31, 31, 30]
Exemple #16
0
import dash_html_components as html
from dash.dependencies import Input, Output

import os

app = dash.Dash(__name__)

#---------------------------------------------------------------
script_dir = os.path.dirname(__file__)  # Script directory
full_path = os.path.join(script_dir,
                         '../Hotel_Reviews.csv')  # Full Directory to the CSV
hotelDf = pd.read_csv(full_path)  # Read csv to Dataframe

#---------------------------------------------------------------
app.layout = html.Div([
    html.Div([dcc.Graph(id='your_graph')], className=''),
    html.P(id='total', className='text-center'),
    html.Div(
        [
            html.Label(['Choose column:'],
                       style={
                           'font-weight': 'bold',
                           "text-align": "center"
                       }),
            dcc.Dropdown(
                id='my_dropdown',
                options=[
                    {
                        'label': 'Positive',
                        'value': '1'
                    },
Exemple #17
0
 dcc.Graph(
     id='map',
     animate=True,
     figure={
         'data': [{
             'lat': df['LAT'],
             'lon': df['LON'],
             'text': df['text'],
             'marker': {
                 'color': df['created_at'],
                 'size': 8,
                 'opacity': 0.6
             },
             'customdata': df['LAT'],
             'type': 'scattermapbox'
         }],
         'layout': {
             'mapbox': {
                 'accesstoken':
                 'pk.eyJ1IjoiY2hyaWRkeXAiLCJhIjoiY2ozcGI1MTZ3MDBpcTJ3cXR4b3owdDQwaCJ9.8jpMunbKjdq1anXwU5gxIw'
             },
             'hovermode': 'closest',
             'height': 500,
             'margin': {
                 'l': 0,
                 'r': 0,
                 'b': 0,
                 't': 0
             }
         }
     }),
Exemple #18
0
 dcc.Graph(
     id='crops',
     figure={
         'data': [
             go.Scatter3d(
                 x=X_embedded[:, 0],
                 y=X_embedded[:, 1],
                 z=carbs,
                 hovertext=names,
                 mode='markers+text',
                 opacity=1,
                 showlegend=True,
                 marker=dict(
                     size=8,
                     color=
                     carbs,  # set color to an array/list of desired values
                     colorscale='Rainbow',  # choose a colorscale
                     showscale=True,
                     opacity=1,
                     colorbar=dict(title='Carbs level'),
                 ))
         ],
         'layout':
         go.Layout(
             title='Crops temperature VS carb level',
             autosize=False,
             width=1200,
             height=800,
             margin=go.Margin(l=50, r=50, b=100, t=100, pad=4),
         ),
     })
Exemple #19
0
import pandas as pd
import os

os.chdir(
    r'C:\Users\Franciszek.Grymula\Documents\_Szkoła\CEIDG-data-visualisation\final_app\scripts'
)

df_corr_feat = pd.read_csv('../data/corrs_and_features.csv', index_col=0)

app = dash.Dash()

app.layout = html.Div([
    html.Div(
        [
            dcc.Graph(id='life-exp-vs-gdp'),
            html.Label('Wybierz metrykę'),
            dcc.Dropdown(id='column',
                         options=[{
                             'label': 'Korelacja',
                             'value': 'correlations'
                         }, {
                             'label': 'Feature importance',
                             'value': 'importance'
                         }],
                         value='importance',
                         clearable=False),
            #    html.Label('Show top'),
            #    dcc.Slider(
            #        id='expectancy-slider',
            #        min=3,
Exemple #20
0
    def layout(self):
        radio_options = ["Statistics", "Data"]
        data = get_data(self.statistics_file)
        key_dropdown_options = [{
            "label": i,
            "value": i
        } for i in list(data["summary_key"].unique())]
        xaxis_dropdown_options = [{
            "label": i,
            "value": i
        } for i in list(data["batch" if self.xaxis ==
                             "date" else "date"].unique())]
        xaxis_dropdown_title = ("Batches to plot"
                                if self.xaxis == "date" else "Dates to plot")

        # Keywords dropdown.
        keyword_elements = [
            html.Label("Keywords to plot:"),
            dcc.Dropdown(
                id=self.key_dropdown_id,
                options=key_dropdown_options,
                multi=True,
            ),
        ]

        # X-axis dropdown.
        xaxis_elements = [
            html.Label(xaxis_dropdown_title, style={"margin-top": 24}),
            dcc.Dropdown(
                id=self.xaxis_dropdown_id,
                options=xaxis_dropdown_options,
                multi=True,
                value=[xaxis_dropdown_options[0]["value"]],
            ),
        ]

        # Radio for switching between data and statistics.
        radio_elements = [
            dcc.RadioItems(
                id=self.radio_id,
                options=[{
                    "label": i,
                    "value": i
                } for i in radio_options],
                value=radio_options[0],
                labelStyle={"display": "inline-block"},
                style={"margin-top": 20},
            ),
        ]
        return html.Div([
            html.Div([
                html.Div(
                    keyword_elements + xaxis_elements + radio_elements,
                    style={
                        "width": "29%",
                        "display": "inline-block",
                        "vertical-align": "top",
                    },
                ),
                html.Div(
                    [
                        dcc.Graph(
                            id=self.graph_id,
                            config={
                                "modeBarButtonsToRemove": ["toImage"],
                                "displaylogo": False,
                            },
                        )
                    ],
                    style={
                        "width": "69%",
                        "display": "inline-block"
                    },
                ),
            ]),
        ])
def layout(matrix):

    drug1 = matrix.combination.lib1.name
    drug2 = matrix.combination.lib2.name

    matrix_df = pd.DataFrame([w.to_dict() for w in matrix.well_results])

    matrix_df = matrix_df.assign(viability=lambda df: 1 - df.inhibition)
    matrix_df = matrix_df[['lib1_conc', 'lib2_conc'] +
                          list(well_metrics.keys())]

    return dbc.Row(
        dbc.Col(
            width=12,
            children=[
                html.Div(
                    className='border p-3 bg-white shadow-sm',
                    children=[
                        dbc.Row([
                            dbc.Col(
                                width=12,
                                className='d-flex flex-row',
                                children=[
                                    dbc.Col(
                                        width='auto',
                                        children=html.H3(
                                            ["Drug combination interaction"],
                                            className='pt-1'),
                                    ),
                                    dbc.Col(width=3,
                                            children=dcc.Dropdown(
                                                id='combo-heatmap-zvalue',
                                                options=list(
                                                    well_metrics.values()),
                                                value='bliss_excess',
                                                searchable=False,
                                                clearable=False)),
                                ]),
                            dbc.Col(html.Hr(), width=12)
                        ]),
                        dbc.Row([
                            dbc.Col(
                                width=7,
                                children=[
                                    dcc.Loading(dcc.Graph(id='combo-heatmap'),
                                                className='gdsc-spinner'),
                                    dcc.Loading(dcc.Graph(id='combo-surface'),
                                                className='gdsc-spinner')
                                ]),
                            dbc.Col(width={
                                "size": 4,
                                "offset": 1
                            },
                                    children=[infoblock_matrix(matrix)])
                        ])
                    ]),
                html.Div(id='combo-values',
                         style={'display': 'none'},
                         children=matrix_df.to_json(date_format='iso',
                                                    orient='split')),
                html.Div(id='drug_names',
                         style={'display': 'none'},
                         children=f"{drug1}:_:{drug2}")
            ]))
Exemple #22
0
# Générer le code HTML
app.layout = html.Div(
    style={'background-color': '#1C2840'},
    children=[
        html.H1("Données COVID-19 dans le monde",
                style={
                    'text-align': 'center',
                    'color': 'white',
                    'padding-top': '2vh',
                    'padding-bottom': '2vh'
                }),
        html.Br(),
        #Dessin de l'élément dans le dashboard

        #Création de la carte des répartitions des cas confirmés dans le monde
        dcc.Graph(id='Carte1', figure=carte1),
        #Création de la carte des répartitions des cas morts dans le monde
        dcc.Graph(id='Carte2', figure=carte2),

        #Graphiques

        #Création de l'histogramme représentant les cas du Covid confirmés en fonction de la date
        dcc.Graph(id='graph1', figure=figure1),
        #Création de l'histogramme représentant les morts du Covid confirmés en fonction de la date
        dcc.Graph(id='graph2', figure=figure2),
        #Création du graphique représentant le nombre de cas confirmé par pays
        dcc.Graph(id='graph3', figure=figure3),
        #Création du graphique représentant le nombre de morts par pays
        dcc.Graph(id='graph4', figure=figure4),
        #Création du graphique représentant le nombre de cas confirmé par pays en fonction du temps
        dcc.Graph(id='graph5', figure=figure5),
Exemple #23
0
            'textAlign': 'center',
            'color': colors['text']
        }
    ),

    html.Div(children='Dash: A web application framework for Python.', style={
        'textAlign': 'center',
        'color': colors['text']
    }),

    dcc.Graph(
        id='example-graph-2',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
            ],
            'layout': {
                'plot_bgcolor': colors['background'],
                'paper_bgcolor': colors['background'],
                'font': {
                    'color': colors['text']
                }
            }
        }
    )
])


if __name__ == '__main__':
    app.run_server(debug=True)
Exemple #24
0
            id='yaxis_raditem',
            options=[
                {
                    'label': 'Time Spent on Site (hours)',
                    'value': 'Time Spent on Site (hours)'
                },
                {
                    'label': 'Amount of Animals',
                    'value': 'Amount of Animals'
                },
            ],
            value='Time Spent on Site (hours)',
            #style={"width": "50%"}
        ),
    ]),
    html.Div([dcc.Graph(id='the_graph')]),
])


#-------------------------------------------------------------------------------------
@app.callback(Output(component_id='the_graph', component_property='figure'), [
    Input(component_id='xaxis_raditem', component_property='value'),
    Input(component_id='yaxis_raditem', component_property='value')
])
def update_graph(x_axis, y_axis):

    dff = df
    # print(dff[[x_axis,y_axis]][:1])

    barchart = px.bar(
        data_frame=dff,
Exemple #25
0
def generate_curves(height=950,
                    width=800,
                    bg_color='white',
                    font_size=10,
                    tick_font_size=8,
                    line_width=0.5):
    # include one graph for all curves, since they have the same x axis
    yvals = 'DEPT'

    cols = list(lf.curves.keys())

    plots = []

    plots.append(['BTVPVS', 'DGRC'])
    plots.append(
        list(
            filter(lambda x: x == 'EWXT' or re.search(r'R[0-9][0-9]P', x),
                   cols)))
    plots.append(['ALCDLC', 'ALDCLC'])
    plots.append(['TNPS'])
    plots.append(['BTCSS', 'BTCS'])

    fig = tools.make_subplots(rows=1,
                              cols=len(plots),
                              shared_yaxes=True,
                              horizontal_spacing=0)

    for i in range(len(plots)):
        for column in plots[i]:
            fig.append_trace(go.Scatter(
                x=lf.curves[column].data,
                y=lf.curves[yvals].data,
                name=column,
                line={
                    'width': line_width,
                    'dash': 'dashdot' if column in plots[1] else 'solid'
                },
            ),
                             row=1,
                             col=i + 1)
            fig['layout']['xaxis{}'.format(i + 1)].update(
                title=generate_axis_title(lf.curves[plots[i][0]]['descr'],
                                          lf.curves[plots[i][0]]['unit']),
                type='log' if column in plots[1] else 'linear')

    fig['data'][1]['xaxis'] = 'x6'
    fig['data'][6]['xaxis'] = 'x7'
    fig['data'][8]['xaxis'] = 'x8'
    fig['data'][11]['xaxis'] = 'x9'

    # DGRC on graph 1
    fig['layout']['xaxis6'] = dict(overlaying='x1',
                                   anchor='y',
                                   side='top',
                                   title=generate_axis_title(
                                       lf.curves['DGRC']['descr'],
                                       lf.curves['DGRC']['unit']))

    # EWXT on graph 2
    fig['layout']['xaxis7'] = dict(overlaying='x2',
                                   anchor='y',
                                   side='top',
                                   title=generate_axis_title(
                                       lf.curves['EWXT']['descr'],
                                       lf.curves['EWXT']['unit']))

    # ALDCLC on graph 3
    fig['layout']['xaxis8'] = dict(overlaying='x3',
                                   anchor='y',
                                   side='top',
                                   title=generate_axis_title(
                                       lf.curves['ALDCLC']['descr'],
                                       lf.curves['ALDCLC']['unit']))

    # BTCS on graph 5
    fig['layout']['xaxis9'] = dict(overlaying='x5',
                                   anchor='y',
                                   side='top',
                                   title=generate_axis_title(
                                       lf.curves['BTCS']['descr'],
                                       lf.curves['BTCS']['unit']))

    # y axis title
    fig['layout']['yaxis'].update(title=generate_axis_title(
        lf.curves[yvals]['descr'], lf.curves[yvals]['unit']),
                                  autorange='reversed')

    for axis in fig['layout']:
        if re.search(r'[xy]axis[0-9]*', axis):
            fig['layout'][axis].update(
                mirror='all',
                automargin=True,
                showline=True,
                title=dict(
                    font=dict(family='Arial, sans-serif', size=font_size)),
                tickfont=dict(family='Arial, sans-serif', size=tick_font_size))

    fig['layout'].update(height=height,
                         width=width,
                         plot_bgcolor=bg_color,
                         paper_bgcolor=bg_color,
                         hovermode='y',
                         legend={'font': {
                             'size': tick_font_size
                         }},
                         margin=go.layout.Margin(r=100))

    return dcc.Graph(figure=fig)
def final_UI(tabs, start_date, end_date, group, report_types,device_date,service_date):
    
    print("Data Type of start_date value = " , str(type(start_date)))
    print("Data of start_date value = " , str(start_date))
    
    print("Data Type of end_date value = " , str(type(end_date)))
    print("Data of end_date value = " , str(end_date))
    
    
    print("Data Type of group value = " , str(type(group)))
    print("Data of group value = " , str(group))
    
    print("Data Type of report_type value = " , str(type(report_types)))
    print("Data of report_type value = " , str(report_types))
    
    print("Data Type of device_date value = " , str(type(device_date)))
    print("Data of device_date value = " , str(device_date))

    print("Data Type of service_date value = " , str(type(service_date)))
    print("Data of service_date value = " , str(service_date))
    if tabs=="tab-1":
        # Filter the data as per the selection of the drop downs
        
        call_analytics_data = calldata[ (calldata["date"]>=start_date) & (calldata["date"]<=end_date) ]
         
        if group  == [] or group is None:
           pass
        else:
           call_analytics_data = call_analytics_data[call_analytics_data["Group"].isin(group)]
           
        graph_data = call_analytics_data
        # Group the data based on the drop down     
        if report_types == "Hourly":
            graph_data = graph_data.groupby("hourly_range")["Call_Direction"].value_counts().reset_index(name = "count")
            x = "hourly_range"
            
            content = call_analytics_data["hourly_range"].value_counts().idxmax()
            title =  "Busiest Hour"
        
            
        elif report_types == "Daily":
            graph_data = graph_data.groupby("date")["Call_Direction"].value_counts().reset_index(name = "count")
            x = "date"
            
            content = call_analytics_data["date"].value_counts().idxmax()
            title =  "Busiest Day"
            
        else:
            graph_data = graph_data.groupby("weekly_range")["Call_Direction"].value_counts().reset_index(name = "count")
            x = "weekly_range"
            
            content = call_analytics_data["weekly_range"].value_counts().idxmax()
            title =  "Busiest WeekDay"
            
           
        # Graph Section
        figure = px.area(graph_data, 
                         x = x, 
                         y = "count",
                         color = "Call_Direction",
                         hover_data=[ "Call_Direction", "count"], 
                         template = "plotly_white")
        figure.update_traces(mode = "lines+markers")
      
      
      
        # Card Section
        total_calls = call_analytics_data["Call_Direction"].count()
        card_1 = card_creation("Total Calls",total_calls, "success")
          
        incoming_calls = call_analytics_data["Call_Direction"][call_analytics_data["Call_Direction"]=="Incoming"].count()
        card_2 = card_creation("Incoming Calls", incoming_calls, "primary")
          
        outgoing_calls = call_analytics_data["Call_Direction"][call_analytics_data["Call_Direction"]=="Outgoing"].count()
        card_3 = card_creation("Outgoing Calls", outgoing_calls, "secondary")
          
        missed_calls = call_analytics_data["Missed Calls"][call_analytics_data["Missed Calls"] == 3].count()
        card_4 = card_creation("Missed Calls", missed_calls, "warning")
          
        max_duration = call_analytics_data["duration"].max()
        card_5 = card_creation("Max Duration", f'{max_duration} min', "dark")
        
        card_6 = card_creation(title, content, "info")
             
      
    
        graphRow0 = dbc.Row([dbc.Col(id='card1', children=[card_1], md=3), dbc.Col(id='card2', children=[card_2], md=3)])
        graphRow1 = dbc.Row([dbc.Col(id='card3', children=[card_3], md=3), dbc.Col(id='card4', children=[card_4], md=3)])
        graphRow2 = dbc.Row([dbc.Col(id='card5', children=[card_5], md=3), dbc.Col(id='card6', children=[card_6], md=3)])
     
        cardDiv = html.Div([graphRow0,html.Br(), graphRow1,html.Br(), graphRow2])
        
    
    
    
    
        # Data Table Section
    
        datatable_data = call_analytics_data.groupby(["Group", "UserID", "UserDeviceType"])["Call_Direction"].value_counts().unstack(fill_value = 0).reset_index()
        if call_analytics_data["Missed Calls"][call_analytics_data["Missed Calls"]==19].count()!=0:
            datatable_data["Missed Calls"] = call_analytics_data.groupby(["Group", "UserID", "UserDeviceType"])["Missed Calls"].value_counts().unstack()[3]
        else:
            datatable_data["Missed Calls"] = 0
            
        datatable_data["Total_call_duration"] = call_analytics_data.groupby(["Group", "UserID", "UserDeviceType"])["duration"].sum().tolist()
        
      
    
        datatable = dt.DataTable(
        id='table',
        columns=[{"name": i, "id": i} for i in datatable_data.columns],
        data=datatable_data.to_dict('records'),
        page_current=0,
        page_size=5,
        page_action='native',
        style_header={'backgroundColor': 'rgb(40, 40, 40)'},
        style_cell={
            'backgroundColor': 'rgb(60, 60, 60)',
            'color': 'white'
        }
        )
        
            
        return [
                dcc.Graph(figure = figure), 
                html.Br() ,
                cardDiv, 
                html.Br(),
                datatable
               ]
 
     #device analytics
    elif tabs == "tab-2":
        if device_date is None or device_date == []: 
            device_analytics_data = device_count(devicedata)
        else:
            device_analytics_data = device_count(devicedata[devicedata["DeviceEventDate"].isin(device_date)])
          
        fig = px.pie(device_analytics_data, names = "Device", values = "Count", color = "Device", hole = .3)
        fig.update_layout(autosize=True,
                          margin=dict(l=0, r=0, t=25, b=20),
                          )
        return dcc.Graph(figure = fig)
    
    #service analytics
    elif tabs == "tab-3":
        if service_date is None or service_date == []:
            service_analytics_data = servicedata["FeatureName"].value_counts().reset_index(name = "Count")
        else:
            service_analytics_data = servicedata["FeatureName"][servicedata["FeatureEventDate"].isin(service_date)].value_counts().reset_index(name = "Count")
        fig = px.pie(service_analytics_data, names = "index", values = "Count",color = "index")
        
        fig.update_layout(autosize=True,
                          margin=dict(l=0, r=0, t=25, b=20),
                          )
        return dcc.Graph(figure = fig)
    
    #if any other return nothing
    else:
        return None
Exemple #27
0
    fig.update_layout(hovermode='closest',
                      mapbox=dict(accesstoken=mapbox_access_token,
                                  style='outdoors',
                                  bearing=2,
                                  center=go.layout.mapbox.Center(lat=-13,
                                                                 lon=-53),
                                  pitch=0,
                                  zoom=3),
                      height=600)
    fig.show()
    return fig


def plot_tweets_per_destination():
    fig = px.bar(tweets_per_dest, x='destination', y='tweets')
    return fig


tweets_on_map = plot_tweets_map()
tweets_per_dest = plot_tweets_per_destination()

layout = html.Div([
    html.H1('Travel mentions on Twitter (per destination)',
            style={"textAlign": "center"}),
    dcc.Graph(id='my-tweets', figure=tweets_on_map),
    html.H1('Most travel destinations mentioned',
            style={"textAlign": "center"}),
    dcc.Graph(id='my-tweets-bar', figure=tweets_per_dest)
])
Exemple #28
0
         "±3%",
         className="fancyValue",
         id="savings-accuracy",
     ),
 ]),
 html.P(
     children=[
         "95% confidence interval for Average Savings result. Smaller is better."
     ],
     className="help",
 ),
 html.Div([
     html.Div([
         dcc.Graph(
             id="accuracy-graph",
             config={
                 "displayModeBar": False
             },
         )
     ])
 ]),
 html.P(children=[
     html.Span(
         "Privacy Cost:",
         className="fancyLabel",
     ),
     html.Span(
         "1.2%",
         className="fancyValue",
         id="privacy-cost",
     ),
 ]),
Exemple #29
0
            ),
            dcc.Dropdown(
                id='crossfilter-code-column',
                options=[{'label': i, 'value': i} for i in codes],
                value='FB'
            ),
        ],style={'width': '49%', 'display': 'inline-block'}),
    ], style={
        'borderBottom': 'thin lightgrey solid',
        'backgroundColor': 'rgb(250, 250, 250)',
        'padding': '10px 5px'
    }),

    html.Div([
        dcc.Graph(
            id='crossfilter-indicator-scatter'
        )
    ], style={'width': '49%', 'display': 'inline-block', 'padding': '0 20'}),

    html.Div([
        dcc.Graph(
            id='crossfilter-model-predictor'
        )
    ], style={'width': '49%', 'display': 'inline-block', 'padding': '0 20'}),
    html.Br(),
    html.Div(id='news')
])


def register_callbacks(app):
    @app.callback(
Exemple #30
0
    'backgroundColor': '#119DFF',
    'color': 'white',
    'padding': '6px'
}

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

df = pd.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/vaccinations.csv")

df_continent = df['location'].value_counts().keys()
df_continent
df_Ind = df[df['location'] == 'India']
print(df_Ind[:5])
layout = html.Div([html.Br(),
    dcc.Tabs([
        dcc.Tab(label='Global',style=tab_style, children=[
            html.H3('Daily Vaccination update in world', style={"textAlign": "center"}),
            dcc.Graph(
                figure=px.line(df, x="date", y="daily_vaccinations", color="location"),
            )
        ], selected_style=tab_selected_style),

        dcc.Tab(label='India', children=[
            html.H3('Daily Vaccination update in India', style={"textAlign": "center"}),
            dcc.Graph(
                figure=px.area(df_Ind, x="date", y="daily_vaccinations", color="location", line_group="location"),

            )
        ], style=tab_style, selected_style=tab_selected_style ),
    ],style=tabs_styles)
])