Example #1
0
        <li>You can select a month of observation with the slider below.</li>
        <li>You can click on a peak to view a detailed graph of what the satellite really saw and how we find a peak in this data.</li>
    </ul>
    <p>For more info, see <a href="https://github.com/dataforgoodfr/batch7_satellite_ges">our website</a>.</p>
    ''')),
    dcc.Slider(id='my-slider',
               min=0,
               max=len(files) - 1,
               step=1,
               value=len(files) - 1,
               marks=get_slider_mark(files)),
    html.Div(id='slider-output-container'),
    # Big Map
    html.Iframe(id='folium-iframe',
                srcDoc=default_folium_map.get_root().render(),
                style={
                    'width': '100%',
                    'height': '400px'
                }),
    # Focus on a single peak
    html.Div(id='div-xco2', children=build_graph(None, None)),
    # Input of a peak ID
    html.P("Sounding_id : "),
    dcc.Input(
        id="input_sounding",
        type="text",
        placeholder="2018082510150705",
    ),
    html.Div(children='''
        Made with Dash: A web application framework for Python.
    '''),
])
Example #2
0
             ],
             className="one-third column",
             id="button",
         ),
     ],
     id="header",
     className="row flex-display",
     style={"margin-bottom": "35px"},
 ),
 html.Div(
     [
         html.Div(
             [
                 html.Iframe(id="map",
                             srcDoc=open("mapas/mapa_base.html",
                                         'r').read(),
                             width=650,
                             height=350)
             ],
             className="pretty_container seven columns",
         ),
         html.Div(
             [
                 html.P(id="radioitems-checklist-output",
                        className="control_label"),
                 html.H6(
                     "Selecciona un algoritmo",
                     className="control_label",
                 ),
                 dcc.RadioItems(
                     id="tipoAlgoritmo",
Example #3
0
     id = "bottom",
      style={'width': '49%',
            'float':'center', 
            'display': 'inline-block'},
     children=[
         html.H4(
             children = "条形变化图",
             style = {
             'font-family':'Microsoft JhengHei'
                     },
                 ),
         html.Iframe(
             style = {
               'Align':'center',
               "margin-left": "100px",
             },
             height = "400",
             width = "600",
             #src = "https://www.youtube.com/embed/lHNApiji9-M",
             src = "//player.bilibili.com/player.html?aid=841044569&bvid=BV1a54y1B7pv&cid=202580784&page=1",
         ),    
     ],
 ),
 html.Div(
     id = "right-bottom",
      style={'width': '49%',
            'float':'right', 
            'display': 'inline-block'},
     children=[
         dcc.Graph(
             id = "bar-plot",
             figure = fig4,
Example #4
0
import dash
import dash_html_components as html
import dash_bootstrap_components as dbc

app = dash.Dash(__name__)

app.layout = html.Div(
    dbc.Container([
        html.Iframe(src='https://www.baidu.com/',
                    style={
                        'width': '100%',
                        'height': '800px'
                    })
    ]))

if __name__ == "__main__":
    app.run_server(debug=True)
Example #5
0
    query = data.query(drug_name + ' == 1')
    race = alt.Chart(query).mark_bar().encode(
        x=alt.X("Race:N", title="Race", axis=alt.AxisConfig(labelAngle=45)),
        y='count()',
        color=alt.Color('Race:N',
                        scale=alt.Scale(scheme='viridis'))).properties(
                            title='Race distribution for ' + drug_name,
                            width=400,
                            height=180)
    return race


app.layout = html.Div([
    html.Iframe(sandbox='allow-scripts',
                id='plot_1',
                height='350',
                width='1200',
                style={'border-width': '0'},
                srcDoc=make_age_gender().to_html()),
    html.Iframe(sandbox='allow-scripts',
                id='plot_2',
                height='350',
                width='1200',
                style={'border-width': '0'},
                srcDoc=make_race().to_html()),
    dcc.Dropdown(id='drugs',
                 options=[
                     {
                         'label': 'Amphet',
                         'value': 'Amphet'
                     },
                     {
Example #6
0
import graphistry as graphistry
from dash.dependencies import Input, Output, State
import pandas as pd
import urllib.request
from pandas.tseries.offsets import *

graphistry.register(api=3,
                    protocol="https",
                    server="hub.graphistry.com",
                    username="******",
                    password="******")

url = "https://raw.githubusercontent.com/uber-web/kepler.gl-data/master/earthquakes/data.csv"
download_file = urllib.request.urlretrieve(url, "data.csv")

df = pd.read_csv("data.csv")
my_src_col = 'DateTime'
my_dest_col = 'EventID'

g = None
g = graphistry.edges(df).bind(source=my_src_col, destination=my_dest_col)
graph = g.plot()

graph_viz = html.Iframe(src=graph, height='800', width='100%')

graphistry_page = html.Div([html.H2("Graphistry Visualization"), graph_viz])


def get_page():
    return graphistry_page
# This script will make regular API calls to http://data-live.flightradar24.com
# to obtain updated total worldwide flights data.
# **This version only loads the site. No callbacks.**
######
import dash
import dash_html_components as html
import requests

url = "https://data-live.flightradar24.com/zones/fcgi/feed.js?faa=1&mlat=1&flarm=1&adsb=1&gnd=1&air=1&vehicles=1&estimated=1&stats=1"
res = requests.get(url,
                   headers={'User-Agent': 'Mozilla/5.0'
                            })  # A fake header is necessary to access the site
data = res.json()
counter = 0
for element in data["stats"]["total"]:
    counter += data["stats"]["total"][element]

app = dash.Dash()

app.layout = html.Div([
    html.Div([
        html.Iframe(src='https://www.flightradar24.com',
                    height=500,
                    width=1200)
    ]),
    html.Div([html.Pre('Active flights worldwide: {}'.format(counter))])
])

if __name__ == '__main__':
    app.run_server()
Example #8
0
        Through a couple of simple patterns, Dash abstracts away all of the
        technologies and protocols that are required to build an
        interactive web-based application.
        Dash is simple enough that you can bind a user interface
        around your Python code in an afternoon.

        Dash apps are rendered in the web browser. You can deploy your apps
        to servers and then share them through URLs.
        Since Dash apps are viewed in the web browser, Dash is inherently
        cross-platform and mobile ready.

        There is a lot behind the framework. To learn more about how it is built
        and what motivated dash, watch our talk from
        [Plotcon](https://plotcon.plot.ly) below
        or read our [announcement letter](https://medium.com/@plotlygraphs/introducing-dash-5ecf7191b503).

        Dash is an open source library, released under the permissive MIT license.
        [Plotly](https://plot.ly) develops Dash and offers a platform for
        deploying, orchestrating, and permissioning dash apps in an enterprise
        environment. If you're interested, [please get in touch](https://plotly.typeform.com/to/seG7Vb).

        ***

    '''.replace('  ', '')),
    html.Iframe(width='100%',
                height='480',
                style={'border': 'none'},
                src='https://www.youtube-nocookie.com/embed/5BAthiN0htc?rel=0')
])
Example #9
0
def GenerateMultiLayouts(days, valoptions, columns, data_locs, GPSMAPLOC):

    if V.TimeSeries:
        timepicker = dcc.DatePickerRange(id='day-picker',
                                         start_date=days[~0],
                                         end_date=days[~0],
                                         min_date_allowed=days[0],
                                         max_date_allowed=days[~0] +
                                         datetime.timedelta(days=1),
                                         display_format='D MMM YYYY')

    else:
        timepicker = dcc.Dropdown(id="data-picker",
                                  options=data_locs,
                                  value=data_locs[0]["value"])

    #HTML
    DASH_layout = html.Div(
        children=[
            html.H1("Sensor DASH"),
            html.Nav(className="nav nav-pills",
                     id="submit-button",
                     children=[
                         dcc.Link(html.Button(
                             'Sensor Dash',
                             className="nav-item nav-link btn",
                             n_clicks=0),
                                  href='/'),
                         dcc.Link(html.Button(
                             'GPS Map',
                             className="nav-item nav-link active btn",
                             n_clicks=0),
                                  href='/gpsmap'),
                     ]),
            timepicker,
            dcc.Dropdown(id="val-select", options=valoptions,
                         value=columns[0]),
            dcc.Graph(id='graph-with-slider'),
            # dcc.Markdown(children=StatusBox),
        ],
        style={'textAlign': 'center'})

    GPS_layout = html.Div([
        html.H1("GPS MAP"),
        html.Nav(className="nav nav-pills",
                 id="submit-button",
                 children=[
                     dcc.Link(html.Button('Sensor Dash',
                                          className="nav-item nav-link btn",
                                          n_clicks=0),
                              href='/'),
                     dcc.Link(html.Button(
                         'GPS Map',
                         className="nav-item nav-link active btn",
                         n_clicks=0),
                              href='/gpsmap'),
                 ]),
        html.Iframe(
            src=app.get_asset_url('GPS_MAP.html'), width="100%", height="500")
    ],
                          style={'textAlign': 'center'})
    return DASH_layout, GPS_layout
        dcc.Markdown('''
            **HINWEIS zu ```0_*.ipynb```**: Bei Notebooks, die alle Datenquellen (**18GB!**) einlesen und verarbeiten (d.h alle Notebooks mit ```0_*``` beginnend.), dauert eine Ausführung **mehrere Stunden**! Dies weil der zur Verfügung gestellte Container nicht sehr performant ist. Lokal auf einem leistungsfähigen Computer (16-Core Processor, 64GB Memory) funktioniert dies aber einwandfrei.
            
            Die aufbereiteten Datenfiles sind aber vorhanden und die restlichen Notebooks können in akzeptabler Zeit ausgeführt werden.
            ''',
                     className='small'),
    ])

    return sidepanel


layout = dbc.Row([
    dbc.Col([create_sidepanel()], md=3),
    dbc.Col([
        html.Iframe(id='notebook-embed',
                    src=notebooks[0]['src'],
                    className='w-100',
                    style={'height': '80vh'}),
    ],
            md=9),
])


def register_callbacks(app):
    @app.callback(
        [
            Output(f"collapse-{idx}", "is_open")
            for idx, _ in enumerate(notebooks)
        ],
        [
            Input(f"group-{idx}-toggle", "n_clicks")
            for idx, _ in enumerate(notebooks)
Example #11
0
def create_layout(app):
    return html.Div(
        [
            Header(app),
            # page 3
            html.Div(
                [
                    html.Div(
                        [
                            html.Div(
                                [
                                    html.H6(["Summary"],
                                            className="subtitle padded"),
                                    html.Table(
                                        make_dash_table(df_seasonsalstats)),
                                ],
                                className="six columns",
                            ),
                            html.Div(
                                [
                                    html.H6(["Observations"],
                                            className="subtitle padded"),
                                    html.P(
                                        "\
                                        Patronage peaks early in the year and steadily rises through \
                                        the Spring until April. The slowest period occurs from June to July, \
                                        before the second annual peak in September. We can make inferences about \
                                        the Fall due to missing data, but we can guess that the trend is generally \
                                        downward until the next anticipated January peak.",
                                    ),
                                    html.P("\
                                        Lap Swim is the most popular activity throughout the year, \
                                        except in March where it is overtaken by Family Swim."
                                           ),
                                ],
                                className="six columns",
                                style={"color": "#696969"},
                            ),
                        ],
                        className="row",
                        style={"margin-bottom": "10px"},
                    ),
                    # Row 3
                    html.Div([
                        html.H6(
                            "Bar Chart of Total Monthly Patronage",
                            className="subtitle padded",
                        ),
                        html.Iframe(src="//plotly.com/~HP-Nunes/239.embed",
                                    width="100%",
                                    height="400")
                    ]),
                    html.Div(
                        [
                            html.Br([]),
                            html.H6(
                                "Descriptive Statistics of Monthly Patronage",
                                className="subtitle padded"),
                            html.Table(
                                make_dash_table(
                                    df_StatisticalSummaryofMonthlyPatronageofBakarIndoorPoolfor2019
                                ),
                                className="tiny-header",
                            )
                        ],
                        style={"overflow-x": "auto"},
                    ),
                ],
                className="sub_page",
            ),
        ],
        className="page",
    )
Example #12
0
adunit = ads.Connection()
addresses = adunit.getAddresses()
addresses = adunit.getAddresses(sqftlot=C.SQFTLOT)
AddressDropdown = dcc.Dropdown(
    id='addressDropdown',
    options=[
        {'label': i, 'value': j} for i, j in zip(addresses.address, addresses.PIN)
    ],
    placeholder='Type your house address here...',
    style={'width': '100%', 'display': 'inline-block', 'vertical-align': 'top'}
)

# create empty map zoomed in on Seattle
Map(location=SEATTLE, zoom_start=INIT_ZOOM, control_scale=True).save("map.html")

MapBlock = html.Iframe(id='map', srcDoc=open("map.html", "r").read(),
                       width="100%", height="75%", style={'display': 'inline-block'})  # height="550"


prices = pd.read_csv("prices_byzipcode.csv")
# Financial Feasibility section


def zipPlaceholder():
    from common_data import app_data
    if app_data.zipcode != 0:
        return str(app_data.zipcode)
    elif app_data.zipcode == 0:
        return 'Find your zipcode here...'


FinFeasibility = html.Div([
        def update_slider(value, all_elements, layout, selected_node):
            new_styles = []
            hidden_edge_ids = []
            nodes = set()

            hidden_edge_ids_per_node_id = dict()

            if selected_node is not None:
                node_id = str(selected_node['id'])
                if node_id is not None and all_elements:
                    for e in all_elements:
                        element = e.get('data')
                        edge_id = element.get('id')
                        id_condition_edge = 'edge[id = "{}"]'.format(edge_id)
                        if element.get('source') == node_id or element.get(
                                'target') == node_id:
                            new_styles.append({
                                'selector': id_condition_edge,
                                'style': {
                                    'width':
                                    self.stylesheetProvider.get_edge_width(
                                        layout['name']),
                                    'hidden':
                                    'false'
                                }
                            })
                        elif element.get('source') is not None:
                            hidden_edge_ids.append(edge_id)
                            if element.get(
                                    'source'
                            ) not in hidden_edge_ids_per_node_id:
                                hidden_edge_ids_per_node_id[element.get(
                                    'source')] = set()
                            hidden_edge_ids_per_node_id[element.get(
                                'source')].add(edge_id)

                            if element.get(
                                    'target'
                            ) not in hidden_edge_ids_per_node_id:
                                hidden_edge_ids_per_node_id[element.get(
                                    'target')] = set()
                            hidden_edge_ids_per_node_id[element.get(
                                'target')].add(edge_id)

                            new_styles.append({
                                'selector': id_condition_edge,
                                'style': {
                                    'hidden': 'true',
                                    'width': '0'
                                }
                            })
                        else:
                            id_condition_node = 'node[id = "{}"]'.format(
                                element.get('id'))
                            if element.get('id') == node_id:
                                color = '#42a1f5'
                            else:
                                color = 'gray'
                            new_styles.append({
                                'selector': id_condition_node,
                                'style': {
                                    'background-color': color
                                }
                            })

            for e in all_elements:
                element = e.get('data')
                if element.get('source') is not None:
                    edge_id = element.get('id')
                    id_condition_edge = 'edge[id = "{}"]'.format(edge_id)
                    if element.get(
                            "id"
                    ) not in hidden_edge_ids and element.get('weight') > value:
                        width = self.stylesheetProvider.get_edge_width(
                            layout['name'])
                    else:
                        width = 0
                        hidden_edge_ids.append(edge_id)

                        if element.get(
                                'source') not in hidden_edge_ids_per_node_id:
                            hidden_edge_ids_per_node_id[element.get(
                                'source')] = set()
                        hidden_edge_ids_per_node_id[element.get('source')].add(
                            edge_id)

                        if element.get(
                                'target') not in hidden_edge_ids_per_node_id:
                            hidden_edge_ids_per_node_id[element.get(
                                'target')] = set()
                        hidden_edge_ids_per_node_id[element.get('target')].add(
                            edge_id)
                    new_styles.append({
                        'selector': id_condition_edge,
                        'style': {
                            'width': width
                        }
                    })
                else:
                    nodes.add(element.get('id'))

            sp = StylesheetProvider()
            for node_id in nodes:
                id_condition_node = 'node[id = "{}"]'.format(node_id)
                if node_id in hidden_edge_ids_per_node_id and len(
                        hidden_edge_ids_per_node_id[node_id]
                ) == len(nodes) - 1:
                    new_styles.append({
                        'selector': id_condition_node,
                        'style': {
                            'width': 0,
                            'height': 0,
                            'color': 'black',
                            'label': '',
                        }
                    })
                else:
                    new_styles.append({
                        'selector': id_condition_node,
                        'style': {
                            'width': sp.get_node_width(layout),
                            'height': sp.get_node_width(layout),
                            'color': 'black',
                            'label': 'data(label)',
                        }
                    })

            children = []
            if selected_node is not None:
                children = html.Iframe(id='pdf-viewer-frame',
                                       src='assets/' + selected_node['label'])

            return value, self.stylesheetProvider.get_stylesheet(
                layout['name']) + new_styles, children
Example #14
0
    html.Label([
        "Select Borough:",
        dcc.RadioItems(id="boro",
                       options=[{
                           'label': i,
                           'value': i
                       } for i in boros],
                       labelStyle={'display': 'inline-block'})
    ]),
    html.Label(["Select Zip Code:", dcc.Dropdown(id="zip")]),
    #html.Label(["Select Your Street Address:",dcc.Dropdown(id="staddr")]),
    html.Div(id='prediction'),
    html.Iframe(id='map',
                srcDoc=ny_map._repr_html_(),
                width='50%',
                height='400',
                style={
                    'width': '49%',
                    'display': 'inline-block'
                }),
    dt.DataTable(id='table',
                 columns=[{
                     "name": i,
                     "id": i
                 } for i in df.columns],
                 data=df.head().to_dict('records'),
                 page_size=50)
    #html.Div(id='prediction')
])


@app.callback(
Example #15
0
def gen_standard_map(df_strava_travs_sliced):
    #First handle empty sliced df case. Create a generic zoomed out map with additional features
    if len(df_strava_travs_sliced) == 0:
        m = folium.Map(location=[36, -108], zoom_start=4, control_scale=True)
        folium.TileLayer('stamenterrain').add_to(m)
        m.save('map.html'
               )  #Save map without routes or markers and create dash layout
        return html.Iframe(id='mainview',
                           srcDoc=open('map.html', 'r').read(),
                           width='100%',
                           height='100%')
    #Slice not empty:
    #Create map based on starting location of last run
    init_coord = df_strava_travs_sliced.iloc[-1]['start_latlng']
    init_coord = ast.literal_eval(init_coord)
    m = folium.Map(location=init_coord, zoom_start=12, control_scale=True)
    folium.TileLayer('stamenterrain').add_to(m)
    #Construct polylines
    for i in df_strava_travs_sliced.index:
        route_coord = polyline.decode(
            df_strava_travs_sliced.loc[i]['map.summary_polyline'])
        folium.PolyLine(
            locations=route_coord,
            tooltip=s_to_easyDate(df_strava_travs_sliced.loc[i]['event_date'])
            + ' - ' + str(df_strava_travs_sliced.loc[i]['name']),
            popup=folium.Popup('<a href=\"https://www.strava.com/activities/' +
                               str(i) + '"target="_blank"> Strava.com </a>'),
            smooth_factor=4,
            weight=4,
        ).add_to(m)
    #### Add location notes markers
    for i in df_locations.index:
        folium.Marker(
            df_locations.loc[i]['coord'],
            tooltip=df_locations.loc[i]['name'],
            popup=df_locations.loc[i]['notes'],
            icon=folium.Icon(color='red', icon='leaf'),
        ).add_to(m)
    ######## Show activity start markers if <= 60 routes sliced
    if len(df_strava_travs_sliced) <= 60:
        for i in df_strava_travs_sliced.index:
            trav_start_coord = polyline.decode(
                df_strava_travs_sliced.loc[i]['map.summary_polyline'])[
                    0]  #Get first coordinate from polyline as start
            folium.Marker(
                trav_start_coord,
                tooltip=s_to_easyDate(
                    df_strava_travs_sliced.loc[i]['event_date']) + ' - ' +
                str(df_strava_travs_sliced.loc[i]['name']),
                popup=folium.Popup(
                    '<a href=\"https://www.strava.com/activities/' + str(i) +
                    '"target="_blank"> Strava.com </a>'),
                icon=folium.Icon(color='green',
                                 icon='cloud',
                                 icon_color='white'),
            ).add_to(m)
    #Save the map and create the mainview
    m.save('map.html')
    return html.Iframe(id='mainview',
                       srcDoc=open('map.html', 'r').read(),
                       width='100%',
                       height='100%')
Example #16
0
         'backgroundColor': 'rgb(250, 250, 250)',
         'padding': '10px 5px'
     }),
 html.Div([
     html.P("Markers Selection:"),
     dcc.Checklist(
         id='markers-tab1',
         options=[{
             'value': x,
             'label': x
         } for x in markers_options],
         #          value=markers_options[0],
         labelStyle={'display': 'inline-block'}),
 ]),
 # Bivariate choropleth matp
 html.Div([html.Iframe(id='map', width='100%', height='600')],
          style={
              'width': '98%',
              'display': 'inline-block',
              'padding': '0 20'
          }),
 # Div for small multiples of the chorpleths
 html.Div(
     [
         html.Div([dcc.Graph(id="choropleth-total-pop", figure=fig1)],
                  style={
                      'width': '23%',
                      'display': 'inline-block',
                      'padding': '0 20'
                  }),
         html.Div([dcc.Graph(id="choropleth-age-01", figure=fig2)],
Example #17
0
                html.Div(children=[

                    html.H6(children='Labels'),
                    dcc.Checklist(
                        id='articlechecklist',
                        options=[{'label': label, 'value': label} for label in event_labels],
                        values=[]
                    ),
                    html.Button('Update labels', id='articlechecklistbutton'),
                    html.Button('Previous article', id='prevarticlebutton'),
                    html.Button('Next article', id='nextarticlebutton'),
                ]),
                html.Div(children=[
                    html.Iframe(id='fullarticleiframe',
                                style={'overflowY': 'scroll', 'height': 400, 'width': 1000,
                                       'overflow': '-moz-scrollbars-vertical',
                                       'padding': 5, 'margin': 0, 'borderRadius': 0, 'border': 'thin lightgrey solid'
                                })
                ])

            ],className="twelve columns",style={'height': 200, 'width': 1300})

            ])
        ]),

    html.P(id='placeholder'),
    html.Div(id='intermediate-value', style = {'display':'none'}),
    html.P(id='updated_df', children=[],style={'display': 'none'})

    #html.P(id='intermediate-value')
Example #18
0
                             'label': 'Africa',
                             'value': 'Africa'
                         }, {
                             'label': 'Americas',
                             'value': 'Americas'
                         }, {
                             'label': 'Oceania',
                             'value': 'Oceania'
                         }],
                         value='World',
                         style=dict(width='30%', verticalAlign="middle"))),
        dbc.Col(
            html.Iframe(
                sandbox='allow-scripts',
                id='plot',
                height='1000',
                width='1500',
                style={'border-width': '0'},
                # need to change the category here under the create_map function
                srcDoc=create_map().to_html())),
    ])
])

app.layout = html.Div([header, content])


@app.callback(dash.dependencies.Output('plot', 'srcDoc'), [
    dash.dependencies.Input('dd-chart', 'value'),
    dash.dependencies.Input('dd-chart2', 'value')
])
def update_plot(alcohol_type, region):
    #Takes in an alcohol_type and calls create_map to update our Altair figure
Example #19
0
                title="Crime category",
                axis=alt.Axis(labelAngle=0)),
        y=alt.Y('count()', title="Count", scale=alt.Scale(domain=(0, 3300))),
        tooltip='count()').properties(
            title="Per hour crime occurrences for the top 4 crimes",
            width=600,
            height=400).add_selection(select_hour).transform_filter(
                select_hour)
    return chart


app.layout = html.Div([

    ### ADD CONTENT HERE like: html.H1('text'),
    html.H1("First dashboard !"),
    html.H2("subtitle"),
    html.H5("The plot"),
    html.Iframe(sandbox="allow-scripts",
                id="plot",
                height="500",
                width="700",
                style={"border-width": "5px"},
                srcDoc=make_plot().to_html()),
    dcc.Markdown("""
        ### Here is a markdown cell

        !>---[here](https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Unico_Anello.png/1920px-Unico_Anello.png)
        """),
])
if __name__ == '__main__':
    app.run_server(debug=True)
Example #20
0
                             Download(id='download_json'),
                             Download(id='download_csv')
                         ], ),
                     ]), ),
             ],
                      body=True),
         ]),
     ],
     lg=5,
 ),
 dbc.Collapse(
     dbc.Col([
         dbc.Row(
             dbc.Card(
                 html.Iframe(id="iframe_mapa",
                             height=400,
                             width=600,
                             style={"border": "none"}),
                 body=True,
             ), ),
         dbc.Row(
             dbc.Card([
                 dbc.Row(html.H6("baixar resultados como:"),
                         justify="center"),
                 html.P(),
                 dbc.Row([
                     dbc.Col(
                         dbc.Button(".CSV",
                                    id='b_download_csv',
                                    block=True,
                                    color="danger",
                                    size="sm",
Example #21
0
def create_map():
    '''
    This functions creates the map off Colombia where the company has stores.
    params:
        none
    returns:
        creates an html for Colombia where each city has information about
        customers purchase frecuency
    '''
	
	df_for_map = get_views.get_view_by_name('tiendas_frecuencia')
	df_for_map["Radio_for_map"]=((df_for_map["valor_neto"])/df_for_map["valor_neto"].mean())*10+5

	# Create the map:
	m_prueba = folium.Map(location=[6.461508, -75.000000],max_zoom=18, zoom_start=6, tiles="cartodbpositron")

	circle="""
	<svg version='1.1' xmlns='http://www.w3.org/2000/svg'
		width='25' height='25' viewBox='0 0 120 120'>
	<circle cx='60' cy='60' r='50'
			fill={} />
	</svg>
	"""

	group1=folium.FeatureGroup(name=circle.format('#FF0000')+"<FONT SIZE=2>Freq. [1,1.25]</font>  ")
	m_prueba.add_child(group1)

	group2=folium.FeatureGroup(name=circle.format('#FF7070')+"<FONT SIZE=2>Freq. [1.25,1.35]</font>", show=False)
	m_prueba.add_child(group2)

	group3=folium.FeatureGroup(name=circle.format('#FF6B22')+"<FONT SIZE=2>Freq. [1.35,1.5]</font>" , show=False)
	m_prueba.add_child(group3)

	group4=folium.FeatureGroup(name=circle.format('#0FFB0E')+"<FONT SIZE=2>Freq. [1.5,1.8]</font>", show=False)
	m_prueba.add_child(group4)

	group5=folium.FeatureGroup(name=circle.format('#019F00')+"<FONT SIZE=2>Freq. > 1.8</font>", show=False)
	m_prueba.add_child(group5)

	for i in range(df_for_map.shape[0]):
		
		sales=round(df_for_map.loc[i,"valor_neto"]/1000000,1)
		sales=f"${sales}M"
		
		html_ = """
		<h2 style="margin-bottom:-10"; align="center">{}</h2>""".format(df_for_map.loc[i,'punto_venta']) + """ <br>
		<b>Total ventas (1 año):</b> {}""".format(sales) + """ <br/>
		<b>Frec. de venta (1 año):</b> {}""".format(round(df_for_map.loc[i,'frequency'],4)) + """ <br/>
		<b>Centro comercial:</b> {}""".format(df_for_map.loc[i,'centro_comercial']) + """ <br/>
		<b>Canal:</b> {}""".format(df_for_map.loc[i,'canal']) + """ <br/>
		<b>Codigo tienda:</b> {}""".format(df_for_map.loc[i,'codigo_tienda']) + """ <br/>
		<b>IDGEO:</b> {}""".format(df_for_map.loc[i,'id_geo'])

		iframe = branca.element.IFrame(html=html_, width=300, height=250)
		popup = folium.Popup(iframe, max_width=305, parse_html=True)

		if (df_for_map.loc[i,"frequency"] > 1) & (df_for_map.loc[i,"frequency"] <= 1.25):
			folium.CircleMarker(radius=df_for_map.loc[i,"Radio_for_map"], 
						location=[df_for_map.loc[i,"latitude"],df_for_map.loc[i,"longitude"]],
						popup=popup,
								color="black",fill=True,fill_color="#FF0000",weight=1,
								fill_opacity=0.7,
						tooltip=f"<FONT SIZE=4><b>Ventas</b>:{sales}</font>").add_to(group1)
		
		elif (df_for_map.loc[i,"frequency"] > 1.25) & (df_for_map.loc[i,"frequency"] <= 1.35):
			folium.CircleMarker(radius=df_for_map.loc[i,"Radio_for_map"], 
						location=[df_for_map.loc[i,"latitude"],df_for_map.loc[i,"longitude"]],
						popup=popup,color="black",fill=True,fill_color="#FF7070",weight=1,
								fill_opacity=0.7,
						tooltip=f"<FONT SIZE=4><b>Ventas</b>:{sales}</font>").add_to(group2)
			
		elif (df_for_map.loc[i,"frequency"] > 1.35) & (df_for_map.loc[i,"frequency"] <= 1.5):
			folium.CircleMarker(radius=df_for_map.loc[i,"Radio_for_map"], 
						location=[df_for_map.loc[i,"latitude"],df_for_map.loc[i,"longitude"]],
						popup=popup,color="black",fill=True,fill_color="#FF6B22",weight=1,
								fill_opacity=0.8,
						tooltip=f"<FONT SIZE=4><b>Ventas</b>:{sales}</font>").add_to(group3)
		
		elif (df_for_map.loc[i,"frequency"] > 1.5) & (df_for_map.loc[i,"frequency"] <= 1.8):
			folium.CircleMarker(radius=df_for_map.loc[i,"Radio_for_map"], 
						location=[df_for_map.loc[i,"latitude"],df_for_map.loc[i,"longitude"]],
						popup=popup,color="black",fill=True,fill_color="#8EFF94",weight=1,
								fill_opacity=0.8,
						tooltip=f"<FONT SIZE=4><b>Ventas</b>:{sales}</font>").add_to(group4)
		else:
			folium.CircleMarker(radius=df_for_map.loc[i,"Radio_for_map"], 
						location=[df_for_map.loc[i,"latitude"],df_for_map.loc[i,"longitude"]],
						popup=popup,color="black",fill=True,fill_color="#2B9A00",weight=1,
								fill_opacity=0.8,
						tooltip=f"<FONT SIZE=4><b>Ventas</b>:{sales}</font>").add_to(group5)
			
	folium.LayerControl(collapsed=False).add_to(m_prueba)
	m_prueba.save('maps/Colombia_map.html')
	##############################
	# Map Layout
	##############################
	map = html.Div(
	    [
			html.H5("Sales frequency and amount per store"),
			html.P("Full Country"),
	        # Place the main graph component here:
	        html.Iframe(srcDoc = open('maps/Colombia_map.html','r').read()
	        	, id="COL_map",width='100%',height=526)
	    ],
	    #className="ds4a-body",
	)

	return map
Example #22
0
def render_content(tab):
    ############################################
    #   Tab 1: 'Home'
    ############################################
    if tab == 'tab-1':
        return html.Div([
                html.Div([
                        dcc.Loading(
                                id="loading-1",
                                children=[
                                        html.Div([
                                        html.Div([
                                                # hack
                                                html.Div(id='model', style={'display':'none'}),
                                                
                                                ############################################
                                                #   Dropdown for selecting ML models
                                                ############################################
                                                html.Label('Select ML model'),
                                                dcc.Dropdown(
                                                        id='model_dropdown',
                                                        options=[
                                                                {'label': 'XGBoost', 'value': 'XGB',},
                                                                {'label': 'Support Vector Machine', 'value': 'SVM'},
                                                                {'label': 'Random Forest', 'value': 'RForest'}
                                                                ],
                                                        value= model_global,
                                                        searchable=False,
                                                        ),
                                                html.Br(),
                                                # hack
                                                html.Div(id='instances', style={'display':'none'}),
                                                
                                                ############################################
                                                #   Input box for selecting instance number
                                                ############################################
                                                html.Label('Select instance from train set'),
                                                dcc.Input(
                                                        id='inp',
                                                        type="number",
                                                        max=350,
                                                        placeholder="number b/w 0 & 350",
                                                        value= instance_global,
                                                        debounce=True,
                                                        style={'height': 35, 'width': '100%'}
                                                        ),
                                                html.Br(),
                                                html.Br(),
                                                html.H6(
                                                        children='LIME Controls',
                                                        style={
                                                                'textAlign': 'center',
                                                                },
                                                        ),
                                                # hack
                                                html.Div(id='kw_update', style={'display':'none'}),
                                                ############################################
                                                #   Dropdown for selecting kernel width
                                                ############################################
                                                html.Label('Select kernel width'),
                                                dcc.Dropdown(
                                                        id='kw_dropdown',
                                                        options=[
                                                                {'label': '0.40', 'value': 0.40},
                                                                {'label': '0.55', 'value': 0.55},
                                                                {'label': '0.60', 'value': 0.60},
                                                                {'label': '0.65', 'value': 0.65},
                                                                {'label': '2.0', 'value': 2.0}
                                                                ],
                                                        value= kw_global,
                                                        searchable=False,
                                                        ),
                                                html.Br(),
                                                # hack
                                                html.Div(id='sample size slider', style={'display':'none'}),
                                                ############################################
                                                #   Slider for selecting sample size
                                                ############################################
                                                html.Label('Select number of samples'),
                                                dcc.Slider(
                                                        id='sample_slider',
                                                        min=0,
                                                        max=2,
                                                        step=1,
                                                        marks={
                                                                0: '5000',
                                                                1: '10000',
                                                                2: '15000'
                                                        },
                                                        value=num_sample_global,
                                                ),
                                                ], className='pretty_container'),
                                                ############################################
                                                #   Information display for model performance
                                                ############################################
                                                html.Div([
                                                html.H6(
                                                        children='Performance of Model',
                                                        style={
                                                                'textAlign': 'center',
                                                                },
                                                        ),
                                                html.Div([
                                                        html.P(id='my_text',children=text_global)
                                                    ]),
                                                html.Br(),
                                                # hack
                                                html.Div(id='performance_update', style={'display':'none'}),
                                                html.Div(id='target'),
                                                ], className='pretty_container'),
                                            ], className='two columns', style={'width':'20%'}),
                                        
                                        ############################################
                                        #   Feature Importance Graph
                                        ############################################
                                        
                                        html.Div([
                                                html.Div([
                                                html.Div([
                                                        html.H4('LIME Explanation'),
                                                        dcc.Markdown('''
                                                                     ---------------------------------------
                                                                     '''),
                                                        html.Img(src='data:image/png;base64,{}'.format(encoded_legend_image.decode()), style={'width':'45%','display': 'inline-block'}),
                                                        ], style={'textAlign': 'center'}),
                                                        dcc.Graph(
                                                                id='LIME',
                                                                figure = {'data': score_data,
                                                                          'layout': {
                                                                                  'height': '55%',
                                                                                  'margin': {
                                                                                          'l': 200, 'b': 20, 't': 30, 'r': 30
                                                                                          },
                                                                                          'xaxis' : {'range':[-.25,.25], 'title':'Feature Effect: Coefficients of LIME explanations', 'automargin': True}, 
                                                                                          'yaxis' : dict(autorange="reversed"),
                                                                                          'paper_bgcolor' : 'rgba(0,0,0,0)',
                                                                                          'plot_bgcolor' : 'rgba(0,0,0,0)'
                                                                                    }
                                                                          }
                                                        ),
                                                html.Br(),
                                                html.Div([
                                                        dcc.Markdown('''
                                                                     ** The above legend indicates the contribution of each feature to the respective classes. Subsequently, it also indicates how much each feature supports/contradicts the black box prediction.
                                                                     '''),
                                                        ], style={'fontSize':14, 'textAlign': 'center'}),
                                                ], className='pretty_container'),
                                                html.Div([
                                                        html.P(id='explainer text',children=[explainer_global])
                                                    ], style={'fontSize':20, 'textAlign': 'center'}),
                                                    html.Div(id='target2'),
                                                ], className='seven columns',),
                                                
                                                 ############################################
                                                #   Black box prediction prob. graph
                                                ############################################
                                                html.Div([
                                                        html.Div([
                                                                html.H6(children='Black-box prediction probabilities'),
                                                                dcc.Graph(
                                                                        id='prediction probability',
                                                                        figure={
                                                                        'data': [go.Bar( x = [round(value_data[2],3), round(value_data[1],3)],
                                                                                              y = ['Non-ruptured', 'Ruptured'],
                                                                                              marker= dict(
                                                                                                      color=['#004c00', '#990000']
                                                                                            ),
                                                                                              orientation='h')], 
                                                                        'layout': {
                                                                                'height': 110,
                                                                                'margin': {'l': 82, 'b': 25, 't': 30, 'r': 10},
                                                                                'xaxis': {'range': [0, 1], 'title':'Prediction Probability of Rupture status', 'automargin': True}, 
                                                                                'paper_bgcolor' : 'rgba(0,0,0,0)',
                                                                                'plot_bgcolor' : 'rgba(0,0,0,0)'
                                                                                }
                                                                        }
                                                                ),
                                                        ], className='pretty_container'),
                                                ############################################
                                                #   Feature value display of instance
                                                ############################################
                                                html.Div([
                                                html.H6(id='feature-label', children='Feature values of Instance {}'.format(instance_global)),
                                                dash_table.DataTable(
                                                        id='feature table',
                                                        columns=[{"name": i, "id": i} for i in dataframe_for_feature_value_table.iloc[:, : 2].columns],
                                                        data=dataframe_for_feature_value_table.to_dict("rows"),
                                                        style_table={
                                                                'maxHeight': '100%',
                                                                'width': '100%',
                                                                'minWidth': '100%',
                                                        },
                                                        style_cell={
                                                                'fontFamily': 'sans-serif',
                                                                'textAlign': 'left',
                                                                'whiteSpace': 'inherit',
                                                                'overflow': 'hidden',
                                                                'textOverflow': 'ellipsis',
                                                        },
                                                        style_header={
                                                                'backgroundColor': 'rgb(230, 230, 230)',
                                                                'fontWeight': 'bold'
                                                        },  
                                                        style_data_conditional=[
                                                                {
                                                                        'if': {'row_index': 'odd'},
                                                                        'backgroundColor': 'rgb(248, 248, 248)'
                                                                }
                                                        ]
                                                ),
                                                ], className='pretty_container'),

                                                ############################################
                                                #   App submission info.
                                                ############################################
                                                html.Div(
                                                        dcc.Markdown('''
                                                                     *This application is part of the following submission:* \n
                                                                     *Identification of Features that Contribute towards Rupture Risk Prediction in Intracranial Aneurysms using LIME*\n
                                                                     *Sachin Nandakumar, Yash Shah, Uli Neimann, Sylvia Saalfeld*                            
                                                                     '''),
                                                        style={
                                                                'display': 'inline-block',
                                                                'fontSize': 11,
                                                                'textAlign': 'right',
                                                                #'color':'white'
                                                        },
                                                ),
                                                html.Br(),
                                                html.Div(id='target3'),
                                ], className='three columns'),
                    ], type=random.choice(['graph','cube']), debug=True)], className="row"),
                
            ])
    ############################################
    #   Tab 2: 'Help'
    ############################################
    elif tab == 'tab-2':
        return html.Div([
                        html.Div([
                                html.Br(),
                                html.Div(
                                        children = [
                                                dcc.Markdown('''
                                                             
                                                             ** LIME aims to create local models – one for each observation of the dataset to be explained. These local models operate in the neighbourhood of the instance (of the dataset) to be explained. **
                            
                                                            Given below are a step-by-step video tutorial and detailed description of this application. It should give you a better understanding of what each component represents.                   
                                                            '''),
                                                ############################################
                                                #   Video tutorial iframe
                                                ############################################
                                                html.Div(
                                                        children=[
                                                                html.Iframe(srcDoc='<video controls width="1500"> <source src="/assets/vid.mp4" type="video/mp4"> Sorry, your browser doesn\'t support embedded videos.</video>',
                                                                            width="1600", height="900", style={'border' : 0}),
                                                                            ],
                                                                style={
                                                                        'vertical-align' : 'middle',
                                                                        'horizontal-align' : 'middle',
                                                                        'textAlign': 'center'
                                                                        
                                                                },
                                                        ),
                                                
                                        ],
                                        style={
                                                    'fontSize': 18,
                                                    'textAlign': 'center'
                                                    },
                                ),  
                        ], className='one columns' , style={'width': '100%'}),
            
                    html.Div([
                        html.Div(
                                children = [
                                ############################################
                                #   Descriptive screenshot of tool
                                ############################################
                                html.Div(
                                        children=[
                                        html.Img(src='data:image/png;base64,{}'.format(encoded_tool_screenshot.decode()), style={'width': '100%',}),
                                ], className="six columns"),
                                
                                ############################################
                                #   Tool description
                                ############################################
                                html.Div(
                                        children=[
                                    html.H5('Description'),
                                    dcc.Markdown('''
                                                 
                                                 **1)** Select model - This dropdown is provided with 3 black-box models (XGBoost, Support Vector Machine & Random Forest) having the best performance evaluated against other 5 models using nested cross-validation.\n
                                                 **2)** Select instance - Each instance corresponds to the aneurysm data of a patient in the dataset. The LIME model explains the black box prediction of the selected instance. Since the training dataset consists of 351 patients, this input box accepts values from 0 to 350.\n
                                                 *Select variables for LIME prediction:* \n
                                                 **3)** The kernel width determines how large the neighbourhood is: A small kernel width means that an instance must be very close to influence the local model, a larger kernel width means that instances that are farther away also influence the model. However, there is no best way to determine the width. The chosen kernel width of **0.65** was where the surrogate model was found to converge locally before global convergence when inspected over a range of values to find stable locality. \n
                                                 **4)** The sample size allows you to choose the number of samples to be perturbed around the instance of interest **(2)** within the kernel width **(3)**.\n
                                                 *Hence LIME model draws **s** number of samples from a normal distribution around the instance **i** within the kernel width **k**. * \n
                                                 **5)** Displays the performance of the selected model **(1)** and the corresponding hyperparameter settings chosen for the model using cross-validation.\n
                                                 **6)** This graph shows the contribution of features towards the black-box model's **(1)** prediction of rupture status of aneurysm of the selected instance **(2)**. The importance/effect of a feature is evaluated by its coefficients in the LIME model (ridge regression). The features are sorted based on the importance of the predicted class.\n
                                                 **7)** Displays the information on whether the instance is predicted correctly/incorrectly by the black-box model on comparison with the actual rupture status from the train set.\n
                                                 **8)** This graph shows the black-box model's prediction probabilities of rupture status of aneurysm of the instance\n
                                                 **9)** Displays the original value of each feature of the instance selected **(2)**. The values of categorical features (Multipel, Lokalisation & Seite) are encoded to numbers before running the machine learning models. Displayed are the encoded as well as the real values of those features.
                                                     '''),
                                ], className="six columns"),
                            ], className='pretty_container twelve columns', style={'fontSize': 13},),
                                                 
# alternate layout. screenshot on another (right hand side) container - need not remove.
#                        html.Div([
#                                html.Div(
#                                        children=[
#                                        html.H6('Reference Screenshot'),
#                                        html.Img(src='data:image/png;base64,{}'.format(encoded_tool_screenshot.decode()), style={'width': '100%', 'height': '100%'}),
#                                ], style={'vertical-align' : 'middle',
#                                        'horizontal-align' : 'middle'
#                                                },),
#                            ], className='pretty_container six columns')
                    ]),
                    
        ]),
Example #23
0
                                            ''')
                                ]),
                                html.Div(id="qr-output"),
                                # Evil hack
                                html.Div(id="qr-output-secondary")
                        ])]),
                dbc.Col(
                    className="col-container",
                    children=[
                        html.Div(
                            id="video-container",
                            className="col-content col-sm-12 col-xs-12",
                            children=[
                                html.H3(id="chart-selector2", children="Video tutorial:"),
                                html.Div([
                                    html.Iframe(id='demo_video',src="https://www.youtube.com/embed/CcEpnrw34zM"),
                                ]),
                            ],
                        ),
                    ],
                ),
            ],
        ),
    ],
)  

def save_file(name, content):
    """Decode and store a file uploaded with Plotly Dash."""
    data = content.encode("utf8").split(b";base64,")[1]
    unique_id = str(uuid.uuid1())
    with open(os.path.join(UPLOAD_DIRECTORY, unique_id+'.zip'), "wb") as fp:
import os
from pathlib import Path
import dash_bootstrap_components as dbc
import dash_html_components as html

BASE_DIR = Path(__file__).resolve().parent.parent
DATA_DIR = BASE_DIR.joinpath('assets')

layout = dbc.Container([
    dbc.Col([
        html.Br(),
        html.Iframe(src=os.path.join("assets", "methodologie.html"),
                    style={
                        'height': '1067px',
                        'width': '100%'
                    }),
    ])
],
                       fluid=True)
Example #25
0
def plot_data(data):
    print("entering plot")

    data, df_heat = clean_data(data)

    # Some recoding for scales and index
    data['activity_code'], factor_list = pd.factorize(data['activity_type'],
                                                      sort=True)
    factor_list = list(factor_list)

    # Summary data
    df_sum = data.groupby(
        [data['activity_type'], data['activity_local_time2'].dt.date]).agg({
            'distance_mi':
            'sum',
            'total_elevation_gain_ft':
            'sum',
            'moving_time2':
            'sum',
            'elapsed_time2':
            'sum',
        }).groupby(level=0).cumsum().reset_index()

    df_sum_athlete = data.groupby(
        [data['athlete_name'], data['activity_local_time2'].dt.date]).agg({
            'distance_mi':
            'sum',
            'total_elevation_gain_ft':
            'sum',
            'moving_time2':
            'sum',
            'elapsed_time2':
            'sum',
        }).groupby(level=0).cumsum().reset_index()

    # Build colorscale
    fix_color_map = {}
    custom_color_scale = []
    activity_type_list = data['activity_type'].unique()

    count = 0

    if len(factor_list) > 1:
        for i in activity_type_list:
            if count > 12:
                count = 0
            fix_color_map[i] = px.colors.cyclical.Phase[count]
            custom_color_scale.append([
                float(factor_list.index(i)) / (len(factor_list) - 1),
                px.colors.cyclical.Phase[count]
            ])
            count = count + 1
    else:
        fix_color_map[0] = px.colors.cyclical.Phase[0]
        custom_color_scale.append([0.0, px.colors.cyclical.Phase[0]])

    custom_color_scale = sorted(custom_color_scale, key=lambda x: x[0])

    # https://plotly.com/python/v3/selection-events/

    fig_sum = px.line(df_sum,
                      x='activity_local_time2',
                      y='distance_mi',
                      labels={
                          "distance_mi": "Value",
                          "activity_local_time2": "Date ",
                          "activity_type": "Activity Type"
                      },
                      color_discrete_map=fix_color_map,
                      template="simple_white",
                      color='activity_type')
    fig_sum.update_traces(connectgaps=True)
    fig_sum.update_layout(yaxis_title="Distance(mi)",
                          title={
                              'text': "Cumulative Club Statistics",
                              'y': 0.9,
                              'x': 0.5,
                              'xanchor': 'center',
                              'yanchor': 'top'
                          })

    fig_sum2 = px.line(df_sum,
                       x='activity_local_time2',
                       y='total_elevation_gain_ft',
                       color_discrete_map=fix_color_map,
                       template="simple_white",
                       color='activity_type')
    fig_sum3 = px.line(df_sum,
                       x='activity_local_time2',
                       y='elapsed_time2',
                       color_discrete_map=fix_color_map,
                       template="simple_white",
                       color='activity_type')
    # fig_sum2.update_traces(connectgaps=True)

    fig_sum.update_layout(updatemenus=[
        dict(
            buttons=list([
                dict(label='Total Distance',
                     method='update',
                     args=[{
                         'y':
                         [fig_sum.data[j].y for j in range(len(fig_sum.data))]
                     }, {
                         'yaxis': {
                             'title': 'Distance(mi)'
                         }
                     }]),
                dict(label='Total Elevation',
                     method='update',
                     args=[
                         {
                             'y': [
                                 fig_sum2.data[j].y
                                 for j in range(len(fig_sum2.data))
                             ]
                         },
                         {
                             'yaxis': {
                                 'title': 'Elevation(ft)'
                             }
                         },
                     ]),
                dict(label='Total Elapsed Time',
                     method='update',
                     args=[
                         {
                             'y': [
                                 fig_sum3.data[j].y
                                 for j in range(len(fig_sum3.data))
                             ]
                         },
                         {
                             'yaxis': {
                                 'title': 'Elapsed_Time(hr)'
                             }
                         },
                     ]),
            ]),
            # direction where the drop-down expands when opened
            direction='down',
            # positional arguments
            x=0.01,
            xanchor='left',
            y=0.99,
            yanchor='bottom',
            font=dict(size=11))
    ])

    fig_sump = px.line(df_sum_athlete,
                       x='activity_local_time2',
                       y='distance_mi',
                       labels={
                           "distance_mi": "Value",
                           "activity_local_time2": "Date ",
                           "athlete_name": "Athlete Name"
                       },
                       color_discrete_map=fix_color_map,
                       template="simple_white",
                       color='athlete_name')
    fig_sump.update_traces(connectgaps=True)
    fig_sump.update_layout(yaxis_title="Distance(mi)",
                           title={
                               'text': "Cumulative Member Statistics",
                               'y': 0.9,
                               'x': 0.5,
                               'xanchor': 'center',
                               'yanchor': 'top'
                           })

    fig_sump2 = px.line(df_sum_athlete,
                        x='activity_local_time2',
                        y='total_elevation_gain_ft',
                        color_discrete_map=fix_color_map,
                        template="simple_white",
                        color='athlete_name')
    fig_sump3 = px.line(df_sum_athlete,
                        x='activity_local_time2',
                        y='elapsed_time2',
                        color_discrete_map=fix_color_map,
                        template="simple_white",
                        color='athlete_name')
    # fig_sum2.update_traces(connectgaps=True)

    fig_sump.update_layout(updatemenus=[
        dict(
            buttons=list([
                dict(label='Total Distance',
                     method='update',
                     args=[{
                         'y': [
                             fig_sump.data[j].y
                             for j in range(len(fig_sump.data))
                         ]
                     }, {
                         'yaxis': {
                             'title': 'Distance(mi)'
                         }
                     }]),
                dict(label='Total Elevation',
                     method='update',
                     args=[
                         {
                             'y': [
                                 fig_sump2.data[j].y
                                 for j in range(len(fig_sump2.data))
                             ]
                         },
                         {
                             'yaxis': {
                                 'title': 'Elevation(ft)'
                             }
                         },
                     ]),
                dict(label='Total Elapsed Time',
                     method='update',
                     args=[
                         {
                             'y': [
                                 fig_sump3.data[j].y
                                 for j in range(len(fig_sump3.data))
                             ]
                         },
                         {
                             'yaxis': {
                                 'title': 'Elapsed_Time(hr)'
                             }
                         },
                     ]),
            ]),
            # direction where the drop-down expands when opened
            direction='down',
            # positional arguments
            x=0.01,
            xanchor='left',
            y=0.99,
            yanchor='bottom',
            font=dict(size=11))
    ])

    # summary data // group
    df1 = data.groupby(['activity_type']).agg({
        'activity_type':
        'count',
        'distance_mi': ['mean', 'sum'],
        'total_elevation_gain_ft': ['mean', 'sum'],
        'moving_time2':
        'mean',
        'elapsed_time2':
        'mean',
    })

    df1.columns = list(map('_'.join, df1.columns))
    df1.index.name = 'type'

    # summary data // athlete
    df2 = data.groupby(['athlete_name']).agg({
        'activity_type':
        'count',
        'distance_mi': ['mean', 'sum'],
        'total_elevation_gain_ft': ['mean', 'sum'],
        'moving_time2': ['mean', 'sum'],
        'elapsed_time2': ['mean', 'sum'],
    })

    df2.columns = list(map('_'.join, df2.columns))
    df2.index.name = 'name'

    fig_par = go.Figure(data=go.Parcoords(
        line=dict(color=data['activity_code'], colorscale=custom_color_scale),
        dimensions=list([
            dict(tickvals=list(range(0,
                                     len(factor_list) + 1)),
                 ticktext=factor_list,
                 label='Activity ID',
                 values=data['activity_code']),
            dict(label='Distance (mi)', values=data['distance_mi']),
            dict(label='Elevation Gain (ft)',
                 values=data['total_elevation_gain_ft']),
            dict(label='Moving Time (hr)', values=data['moving_time2']),
            dict(label='Elapsed Time (hr)', values=data['elapsed_time2']),
        ])))

    fig_par.update_layout(
        title={
            'text': "Activity Parallel Coordinates",
            'y': 1,
            'x': 0.5,
            'xanchor': 'center',
            'yanchor': 'top'
        })

    fig_hist = px.histogram(data,
                            x="activity_type",
                            labels={
                                "activity_type": "Activity Type",
                            },
                            color='activity_type',
                            color_discrete_map=fix_color_map,
                            template="simple_white")
    fig_hist.update_layout(
        title={
            'text': "Count Of Activity Types",
            'y': 0.95,
            'x': 0.5,
            'xanchor': 'center',
            'yanchor': 'top'
        })

    data['activity_start_hour'] = data['activity_local_time2'].dt.hour
    fig_hist2 = px.histogram(data,
                             x="activity_start_hour",
                             labels={
                                 "activity_start_hour": "Time Of Day",
                             },
                             color='activity_type',
                             color_discrete_map=fix_color_map,
                             template="simple_white")
    fig_hist2.update_layout(
        title={
            'text': "Activity Start Time",
            'y': 0.95,
            'x': 0.5,
            'xanchor': 'center',
            'yanchor': 'top'
        })
    #
    # fig.write_html("strava1.html")

    df1['moving_time2_mean'] = pd.to_timedelta(df1['moving_time2_mean'],
                                               unit='h').apply(time_format)
    df1['elapsed_time2_mean'] = pd.to_timedelta(df1['elapsed_time2_mean'],
                                                unit='h').apply(time_format)
    df1 = df1.round(2)

    df2['moving_time2_mean'] = pd.to_timedelta(df2['moving_time2_mean'],
                                               unit='h').apply(time_format)
    df2['elapsed_time2_mean'] = pd.to_timedelta(df2['elapsed_time2_mean'],
                                                unit='h').apply(time_format)
    df2 = df2.round(2)

    header_color = 'grey'
    row_even_color = 'lightgrey'
    row_odd_color = 'white'

    fig_table = go.Figure(data=[
        go.Table(
            header=dict(values=[
                'Activity Type', 'Count', 'Average Distance (mi)',
                'Total Distance (mi)', 'Average Elevation Gain (ft)',
                'Total Elevation Gain (ft)', 'Average Moving Time (hrs)',
                'Average Elapsed Time (hrs)'
            ],
                        line_color='darkslategray',
                        fill_color=header_color,
                        align=['left', 'center'],
                        font=dict(color='Black')),
            cells=dict(
                values=[
                    df1.index, df1.activity_type_count, df1.distance_mi_mean,
                    df1.distance_mi_sum, df1.total_elevation_gain_ft_mean,
                    df1.total_elevation_gain_ft_sum, df1.moving_time2_mean,
                    df1.elapsed_time2_mean
                ],
                line_color='darkslategray',
                # 2-D list of colors for alternating rows
                fill_color=[[
                    row_odd_color, row_even_color, row_odd_color,
                    row_even_color
                ] * 8],
                align=['left'],
            ))
    ])

    df2.sort_values(by=['moving_time2_sum'], ascending=False, inplace=True)

    fig_table2 = go.Figure(data=[
        go.Table(
            header=dict(values=[
                'Athlete Name', 'Count', 'Average Distance (mi)',
                'Total Distance (mi)', 'Average Elevation Gain (ft)',
                'Total Elevation Gain (ft)', 'Total Moving Time (hrs)',
                'Average Elapsed Time (hrs)'
            ],
                        line_color='darkslategray',
                        fill_color=header_color,
                        align=['left', 'center'],
                        font=dict(color='Black')),
            cells=dict(
                values=[
                    df2.index, df2.activity_type_count, df2.distance_mi_mean,
                    df2.distance_mi_sum, df2.total_elevation_gain_ft_mean,
                    df2.total_elevation_gain_ft_sum, df2.moving_time2_sum,
                    df2.elapsed_time2_mean
                ],
                line_color='darkslategray',
                # 2-D list of colors for alternating rows
                fill_color=[[
                    row_odd_color, row_even_color, row_odd_color,
                    row_even_color
                ] * 8],
                align=['left'],
            ))
    ])

    m = folium.Map([40.087424, -105.190813], zoom_start=11)
    # convert to (n, 2) nd-array format for heatmap
    gpx_track = df_heat[['Latitude', 'Longitude']].values
    # plot heatmap
    m.add_child(plugins.HeatMap(gpx_track, radius=7))
    heat_output = m._repr_html_()
    # m.save(os.path.join(os.path.dirname(__file__), 'assets', "heatmap.html"))
    # m.save(heat_output)
    # print(heat_output)

    graph1 = dcc.Graph(id='graph1', figure=fig_hist, className="six columns")
    graph1_2 = dcc.Graph(id='graph1_2',
                         figure=fig_hist2,
                         className="six columns")

    graph2 = dcc.Graph(id='graph2',
                       figure=fig_par,
                       className="twelve columns",
                       style={'height': '500px'})

    table = dcc.Graph(id='table1',
                      figure=fig_table,
                      className="twelve columns")

    graph4 = dcc.Graph(id='graph4', figure=fig_sum, className="six columns")
    graph4_2 = dcc.Graph(id='graph4_2',
                         figure=fig_sump,
                         className="six columns")

    table2 = dcc.Graph(id='table2',
                       figure=fig_table2,
                       className="twelve columns")

    map_plot = html_dash.Iframe(id='map',
                                srcDoc=heat_output,
                                width='90%',
                                height='500')

    row1 = html_dash.Div(children=[table])

    row2 = html_dash.Div(children=[graph1, graph1_2], )

    row3 = html_dash.Div(children=[
        graph2,
    ], )

    row4 = html_dash.Div(children=[map_plot])

    row5 = html_dash.Div(children=[graph4, graph4_2])

    row6 = html_dash.Div(children=[table2])

    layout = html_dash.Div(children=[row1, row2, row3, row4, row5, row6])

    return layout
Example #26
0
    ]),    

    ### ADD CONTENT HERE like: html.H1('text'),
    html.H1('This is my first dashboard'),
    html.H2('This is a subtitle'),

    html.H3('Here is an image'),
    html.Img(src='https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Unico_Anello.png/1920px-Unico_Anello.png', 
            width='10%'),

    html.H3('Here is our first plot:'),
    html.Iframe(
        sandbox='allow-scripts',
        id='plot',
        height='500',
        width='1000',
        style={'border-width': '0'},
        ################ The magic happens here
        srcDoc=make_plot().to_html()
        ################ The magic happens here
        ),

    dcc.Markdown('''
    ### Dash and Markdown
                '''),

    ## these two components are related to dropdown
    dcc.Dropdown(
        id='demo-dropdown',
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': 'Montreal', 'value': 'MTL'},
Example #27
0
                     n_clicks=0,
                     children='Submit',
                     style={'padding': '0 30px'})
     ],
     style={
         'color': 'white',
         'text-align': 'center',
         'background-color': '#1e2c45',
         'margin': '0',
     }),
 html.Div([
     html.Iframe(id='google-frame',
                 src='',
                 style={
                     'width': '48%',
                     'float': 'left',
                     'height': '625px',
                     'margin-left': '25px',
                     'margin-top': '15px',
                     'frameBorder': '0'
                 }),
     html.Iframe(id='encode-frame',
                 src='',
                 style={
                     'width': '48%',
                     'float': 'left',
                     'height': '625px',
                     'margin-right': '23px',
                     'margin-top': '15px',
                     'frameBorder': '0'
                 })
 ],
Example #28
0
    html.H1('aaaaaaa'),

    ### ADD CONTENT HERE like: html.H1('text'),
    html.H1('TfsdfaSAA TITLE'),
    html.H2('This is a subtitle'),
    html.H3('Here is an image'),
    html.Img(
        src=
        'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/Unico_Anello.png/1920px-Unico_Anello.png',
        width='20%'),
    html.Iframe(
        sandbox='allow-scripts',
        id='plot',
        height='500',
        width='500',
        style={'border-width': '1px'},

        ################ The magic happens here
        srcDoc=make_plot([1950, 2000]).to_html()
        ################ The magic happens here
    ),
    dcc.Markdown('''
        ASDFSAFSAFAFSDFAJFDSAJK:KADFS
        print("helo")
    '''),
    dcc.Dropdown(
        options=[
            {
                'label': 'New York',
                'value': 'NYC'
            },
                    html.P('The fund can complement your portfolio.', className = 'blue-text'),

                    html.Strong('The fund is designed for:'),
                    html.P('The fund is designed for investors who are looking for a flexible \
                            global investment and sub-investment grade fixed income portfolio \
                            that has the ability to alter its exposure with an emphasis on interest \
                            rates, currencies and credit markets and that seeks to generate returns \
                            through different market conditions with a riskier investment strategy \
                            than GS Strategic Absolute Return Bond I Portfolio.', className = 'blue-text' ),

                ], className = "four columns" ),

                html.Div([
                    html.H6(["Performance (Indexed)"],
                            className = "gs-header gs-table-header padded"),
                    html.Iframe(src="https://plot.ly/~jackp/17553.embed?modebar=false&link=false&autosize=true", \
                            seamless="seamless", style=dict(border=0), width="100%", height="250")
                ], className = "eight columns" ),

            ], className = "row "),

            # Row 2.5

            html.Div([

                html.Div([
                    html.H6('Performance (%)', className = "gs-header gs-text-header padded"),
                    html.Table( make_dash_table( df_perf_pc ), className = 'tiny-header' )
                ], className = "four columns" ),

                html.Div([
                    html.P("This is an actively managed fund that is not designed to track its reference benchmark. \
Example #30
0
                                       children="Type your arrival address."),
                                dcc.Input(id="add_end",
                                          type="text",
                                          placeholder=""),
                            ],
                        ),
                        html.Button('Submit', id='button'),
                    ],
                ),
                html.Div(id="display_map",
                         children=[
                             html.P(id="map-title",
                                    children=" Enjoy your trip"),
                             html.Iframe(id='map',
                                         srcDoc=open(
                                             my_input().path_initial_map,
                                             'r').read(),
                                         width='100%',
                                         height='600'),
                         ])
            ],
        ),
    ],
)

# @app.callback(
#     Output("summary-user-selection", "children"),
#     [Input("add_start", "value"), Input("add_end", "value")],
# )


@app.callback(