def usaMap(dataFrame, loc, var, color, title):
    #make a map of the usa that shows relative amounts of var
    #usaMap(dataSubset3, 'STATE_ABBR', 'AVG_REL_EST_TOTAL', 'Blues', 'Average Release Estimate Total Per State Over Time')

    fig = go.Figure(data=go.Choropleth(
        #set location equal to dataframe column (for example: dataFrame['STATE_ABBR'])
        locations=dataFrame[loc],
        #set data equal to datafram column corresponding to variable passed as arg
        z=dataFrame[var],
        #set location mode to United States
        locationmode='USA-states',
        #set colorscale to color scheme passed as arg
        colorscale=color,
    ))

    fig.update_layout(
        #set the title to the title passed as arg
        title_text=title,
        #set the scope to usa so that fig only shows United States map
        geo_scope='usa',
    )

    #make filename and write the figure to html – opens automatically
    filename = 'usamap_' + title.replace(' ', '_') + '.html'
    fig.write_html(filename, auto_open=True)
def make_plot(locations, z):
    data = [
        go.Choropleth(
            locations=locations,
            z=z,
            text=locations,
            locationmode="ISO-3",
            autocolorscale=True,
            marker=go.choropleth.Marker(
                line=go.choropleth.marker.Line(color='rgb(0,0,0)', width=0.5)),
            colorbar=go.choropleth.ColorBar(ticksuffix='%',
                                            title='% of children',
                                            len=0.5),
        )
    ]

    layout = go.Layout(
        height=700,
        width=700,
        margin={
            "t": 0,
            "b": 0,
            "l": 0,
            "r": 0
        },
        geo=go.layout.Geo(
            #         resolution=50,
            showframe=True,
            showcoastlines=True,
            showcountries=True,
            projection=go.layout.geo.Projection(type='mercator')),
    )

    fig = go.Figure(data=data, layout=layout)
    iplot(fig)
示例#3
0
def choropleth_scores_plot(state_values,
                           date,
                           cmax,
                           cmin,
                           filename='choropleth.svg'):

    fig = go.Figure(data=go.Choropleth(
        locations=
        states,  #['AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'],
        locationmode='USA-states',
        colorscale='Viridis',
        z=state_values,
        marker=dict(
            line=dict(color='rgb(255,255,255)', width=2),
            #                      cmax = cmax,
            #                      cmin = cmin,
            #colorbar= dict(title='Average Polarity<br> Scorescore/tweet'),
        ),
        zmax=0,
        zmin=cmin,
    ))

    fig.update_layout(
        title_text='Number of Tweets: ' + date,
        font=dict(size=24),
        geo_scope='usa',
    )

    iplot(fig)
    fig.write_image(filename, format='png', width=1400, height=1000, scale=2)
示例#4
0
def create_plotly(df):

    df_st = df.copy()

    for col in df_st.columns:
        df_st[col] = df_st[col].astype(str)

    scl = [
        [0.0, 'rgb(242,240,247)'],
        [0.2, 'rgb(218,218,235)'],
        [0.4, 'rgb(188,189,220)'],
        [0.6, 'rgb(158,154,200)'],
        [0.8, 'rgb(117,107,177)'],
        [1.0, 'rgb(84,39,143)']
    ]


    df_st['text'] = df_st['State'] + '<br>' + \
        'Profit' + df_st['Profit'] + ' Sales ' + df_st['Sales']

    data = [go.Choropleth(
        colorscale=scl,
        autocolorscale=True,
        locations=df_st['Code'],
        z=df_st['Profit'].astype(float),
        locationmode='USA-states',
        text=df_st['text'],
        marker=go.choropleth.Marker(
            line=go.choropleth.marker.Line(
                color='rgb(255,255,255)',
                width=2
            )),
        colorbar=go.choropleth.ColorBar(title="Sale&Profit$$"))]
    return data
def plotStates(colored, title, label):
    """
    Docstring: Create plotly visualization of US states colored by the variable colored
    Currently only using stateData, but could be generalized to accept any dataset
    """
    #scl = [[0.0, '#ffffff'],[0.2, '#ff9999'],[0.4, '#ff4d4d'],[0.6, '#ff1a1a'],[0.8, '#cc0000'],[1.0, '#4d0000']] # reds
    data = [
        go.Choropleth(
            #colorscale = scl,
            colorscale='RdBu',
            autocolorscale=False,
            locations=stateData['Initials'],
            z=stateData[colored].astype(float),
            locationmode='USA-states',
            text=stateData['State'],
            marker=go.choropleth.Marker(line=go.choropleth.marker.Line(
                color='rgb(255,255,255)', width=2)),
            colorbar=go.choropleth.ColorBar(title=label))
    ]
    layout = go.Layout(
        title=go.layout.Title(text=title),
        geo=go.layout.Geo(
            scope='usa',
            projection=go.layout.geo.Projection(type='albers usa'),
            showlakes=True,
            lakecolor='rgb(255, 255, 255)'),
    )
    fig = go.Figure(data=data, layout=layout)
    plotly.offline.plot(fig, auto_open=True)
示例#6
0
def worldgraph1(ctry, data, ccode, title="Worldwide Happiness", reverse=False):
    fig = go.Figure(data=go.Choropleth(
        locations=ccode,
        z=data,
        text=ctry,
        autocolorscale=True,
        reversescale=reverse,
        marker_line_color="darkgray",
        marker_line_width=0.5,
        colorbar_title="Happiness",
    ))
    fig.update_layout(
        title_text=title,
        geo=dict(showframe=False,
                 showcoastlines=False,
                 projection_type="equirectangular"),
        annotations=[
            dict(
                x=0.55,
                y=0.1,
                xref="paper",
                yref="paper",
                text="Source: Worldwide Happiness Report, 2019",
                showarrow=False,
            )
        ],
    )
    fig.show()
示例#7
0
def make_plot(x, z):
    data = [
        go.Choropleth(
            locations=x,
            z=z,
            text=x,
            locationmode="country names",
            autocolorscale=True,
            marker=go.choropleth.Marker(
                line=go.choropleth.marker.Line(color='rgb(0,0,0)', width=0.5)),
            colorbar=go.choropleth.ColorBar(len=0.5),
        )
    ]

    layout = go.Layout(height=700,
                       width=700,
                       margin={
                           "t": 0,
                           "b": 0,
                           "l": 0,
                           "r": 0
                       },
                       geo=go.layout.Geo(showframe=True,
                                         showcoastlines=True,
                                         showcountries=True,
                                         projection=go.layout.geo.Projection(
                                             type='mercator')))

    fig = go.Figure(data=data, layout=layout)
    iplot(fig)
示例#8
0
def makeChoropleth(dates, types, countries, location):

    chorodata = mannschaft.loc[
        (mannschaft['Date'] >= dates[0]) & (mannschaft['Date'] <= dates[1]) &
        (mannschaft['Opponent'].isin(types)) &
        (mannschaft['Location'].isin(locations))].copy()

    chorodata = chorodata.groupby(['code', 'Opponent'
                                   ]).sum()['German Goals'].reset_index()
    chorodata = pd.merge(
        mannschaft[['code',
                    'Opponent']].drop_duplicates().reset_index().drop('index',
                                                                      axis=1),
        chorodata,
        on=['code', 'Opponent'],
        how='outer')

    chorodata = chorodata.loc[chorodata['Opponent'].isin(countries)]

    data = [
        go.Choropleth(
            locations=chorodata['code'],
            z=chorodata['German Goals'],
            colorscale='Viridis',
            zmin=0,
            zmax=mannschaft.groupby('Opponent').sum()['German Goals'].max())
    ]

    layout = go.Layout(title='I do not know',
                       geo=dict(center=dict(lon=-60, lat=-12),
                                projection=dict(scale=2)))

    return go.Figure(data=data, layout=layout)
示例#9
0
def update_figure(selected, cause, year):
    def title(text):
        if text == "fire_size":
            return "Acres Burned"
        elif text == "fire_count":
            return "Wildfire Count"
        else:
            return "FIRE"

    if year == 2016:
        state_df = df.groupby(['state',
                               'stat_cause_descr']).sum().reset_index()
    else:
        df_f = df[df['fire_year'] == year]
        state_df = df_f.groupby(['state', 'fire_year',
                                 'stat_cause_descr']).sum().reset_index()

    trace = go.Choropleth(
        locations=state_df[state_df['stat_cause_descr'] == cause]['state'],
        locationmode='USA-states',
        z=state_df[state_df['stat_cause_descr'] == cause][selected],
        text=state_df[state_df['stat_cause_descr'] == cause]['state'],
        autocolorscale=False,
        colorscale="Reds",
        reversescale=False,
        marker={'line': {
            'color': 'rgb(180,180,180)',
            'width': 0.5
        }},
        colorbar={
            "thickness": 10,
            "len": 0.4,
            "x": -0.1,
            "y": 0.7,
            "xanchor": 'left',
            'title': {
                "text": title(selected),
                "side": "top"
            }
        })
    return {
        "data": [trace],
        "layout":
        go.Layout(title={
            'text': 'Wildfire Caused By ' + cause,
            'yanchor': 'top',
            'x': 0.5,
            'y': 0.9
        },
                  clickmode='event+select',
                  paper_bgcolor='white',
                  plot_bgcolor='white',
                  height=600,
                  width=800,
                  geo={
                      'scope': 'usa',
                      'bgcolor': 'rgba(0,0,0,0)'
                  },
                  margin=dict(l=0, r=0, b=0, t=0, pad=0))
    }
示例#10
0
def horoplethMap(df_data):
    df = pd.read_csv(
        'https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv'
    )
    fig = go.Figure(data=go.Choropleth(
        locations=df['CODE'],
        z=df_data['KMeans'],
        text=df_data['country'],
        colorscale='Blues',
        autocolorscale=False,
        reversescale=True,
        marker_line_color='darkgray',
        marker_line_width=0.5,
        colorbar_title='Clustering',
    ))

    fig.update_layout(
        title_text='KMeans Clustering Plot',
        geo=dict(showframe=False,
                 showcoastlines=False,
                 projection_type='equirectangular'),
        annotations=[
            dict(
                x=0.55,
                y=0.1,
                xref='paper',
                yref='paper',
                text=
                'Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
                CIA World Factbook</a>',
                showarrow=False)
        ])
    py.image.save_as(fig, filename='horoplethMap.png')
示例#11
0
def makeChoropleth(dates, types, countries, locations):

    chorodata = zika.loc[(zika['report_date'] >= dates[0]) & (zika['report_date'] <= dates[1]) &
                        (zika['report_type'].isin(types)) & (zika['location'].isin(locations))].copy()

    chorodata = chorodata.groupby(['code', 'country']).sum()['value'].reset_index()
    chorodata = pd.merge(zika[['code', 'country']].drop_duplicates().reset_index().drop('index', axis = 1),
                         chorodata, on=['code', 'country'], how='outer')

    chorodata = chorodata.loc[chorodata['country'].isin(countries)]

    data = [
        go.Choropleth(
            locations = chorodata['code'],
            z = chorodata['value'],
            colorscale = 'Viridis',
            zmin = 0,
            zmax = zika.groupby('country').sum()['value'].max()
        )
    ]

    layout = go.Layout(
        title = 'Zika Cases by Country',
        geo = dict(
            center = dict(lon = -60, lat = -12),
            projection = dict(scale = 2)
        )
    )

    return go.Figure(data = data, layout = layout)
示例#12
0
def update_figure(selected_si):

    if selected_si == 0:
        selected_si = '0.0'
    elif selected_si == 1:
        selected_si = '1.0'

    column = 'SI_'+ str(selected_si)

    trace = go.Choropleth(
        locations=sus_df['code'],
        z=sus_df[column].astype(float),
        locationmode='USA-states',
        colorscale='Greens',
        autocolorscale=False,
        # hovertext=sus_df['text'], # hover text
        marker_line_color='white', # line markers between states
        colorbar={"thickness": 10,"len": 0.55,"x": 0.9,"y": 0.55,'outlinecolor':'white',
                  'title': {#"text": 'SI',
                            "side": "top"}}
        )

    return {"data": [trace],
            "layout": go.Layout(title={'text':'Sustainability Indexes of U.S. States',
                                        'y':0.9,
                                        },
                                height=350,
                                geo = dict(
                                    scope='usa',
                                    projection=go.layout.geo.Projection(type = 'albers usa'),
                                    showlakes=False, # lakes
                                    ),
                                margin={'t':10,'b':0,'l':10,'r':10})}
示例#13
0
def Plotter(mapName, scl, values):

    data = [
        go.Choropleth(
            colorscale=scl,
            autocolorscale=False,
            locations=list(stateDict.values()),
            z=values,
            locationmode='USA-states',
            text=[i[0] for i in locs],
            marker=go.choropleth.Marker(line=go.choropleth.marker.Line(
                color='rgb(255,255,255)', width=2)),
            colorbar=go.choropleth.ColorBar(title=mapName))
    ]

    layout = go.Layout(
        title=go.layout.Title(text=mapName),
        geo=go.layout.Geo(
            scope='usa',
            projection=go.layout.geo.Projection(type='albers usa'),
            showlakes=True,
            lakecolor='rgb(255, 255, 255)'),
    )

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

    plotly.offline.plot(fig, filename=(mapName + ".html"))
def location_map_function(country):
    '''
        Returns a world map where the given country is highlighted.
        As only data provided are the ones of the country - only the
        country is coloured in the output map.
    '''
    trace2 = go.Choropleth(locations=[country],
                           z=[1],
                           text=country,
                           autocolorscale=True,
                           locationmode='country names',
                           showscale=False)
    return {
        "data": [trace2],
        "layout":
        go.Layout(height=500,
                  margin=go.layout.Margin(l=0, r=0, b=0, t=0, pad=4),
                  geo={
                      'showframe': False,
                      'showcountries': True,
                      'showcoastlines': True,
                      'projection': {
                          'type': "miller"
                      }
                  })
    }
示例#15
0
    def world_map(self, df, x_col, y_col, label_col, chart_title):

        map_json = {
            'data': [
                go.Choropleth(locations=df[x_col],
                              z=df[y_col],
                              text=df[label_col],
                              colorscale='blues',
                              marker_line_color='darkgray',
                              marker_line_width=0.5,
                              colorbar_title="Total<br>RSVP's")
            ],
            'layout':
            go.Layout(
                #                title_text='Worldwide RSVP Map',
                width=plot_w,
                #                height=plot_h,
                margin={
                    'b': 0,
                    't': 0,
                    'r': 0,
                    'l': 0
                },
                clickmode='event+select',
                geo=dict(showframe=False,
                         showcoastlines=False,
                         landcolor='rgb(230, 230, 230)',
                         showland=True))
        }

        return map_json
示例#16
0
def display_output(rows, columns, titulo, varname):
    df_ciudades_ant_cuenta = pd.DataFrame(rows,
                                          columns=[c['name'] for c in columns])

    fig = go.Figure(data=go.Choropleth(
        locations=df_ciudades_ant_cuenta['ciudad'],  # Spatial coordinates
        z=df_ciudades_ant_cuenta['cuenta'].astype(
            float),  # Data to be color-coded
        geojson=geoJSON,
        featureidkey="properties.name",
        colorscale='Blues',
        colorbar_title=varname,
        locationmode='geojson-id'))

    fig.update_geos(fitbounds="locations",
                    visible=False,
                    showcountries=False,
                    countrycolor="Black",
                    showsubunits=False)
    fig.update_layout(
        width=1000,
        height=1000,
        geo=dict(
            scope='south america',
            projection=go.layout.geo.Projection(type='mercator'),
            showlakes=True,  # lakes
            lakecolor='rgb(255, 255, 255)'),
        title_text=titulo,
        font=dict(family="Courier New, monospace", size=25, color="#7f7f7f"))

    return fig
示例#17
0
def map_maker(year):
    dff = df[df['Year'] == year]
    print(dff.head(5))
    trace = [
        go.Choropleth(
            locations=dff['Code'],
            locationmode='USA-states',
            z=dff['Score_Classification'],
            text=dff['Legal Name'],
            colorscale="YlOrRd",
        )
    ]
    layout = go.Layout(autosize=True,
                       hovermode='closest',
                       geo_scope='usa',
                       showlegend=True,
                       height=700,
                       margin=dict(l=20, r=20, t=20, b=20),
                       mapbox={
                           'accesstoken': mapbox_access_token,
                           'bearing': 0,
                           'center': {
                               'lat': 38,
                               'lon': -94
                           },
                           'pitch': 30,
                           'zoom': 3,
                           'style': 'light'
                       })
    return {'data': trace, 'layout': layout}
示例#18
0
def update_figure(selected):
    """Generate choropleth based on selected option."""
    x_values = [x[0] for x in price_levels[selected]]
    y_values = [x[1] for x in price_levels[selected]]

    trace = go.Choropleth(
        type="choropleth",
        locations=x_values,
        locationmode="country names",
        colorscale=complete[selected],
        colorbar=go.choropleth.ColorBar(ticksuffix="", title="Percent", len=0.5),
        z=y_values,
    )

    return {
        "data": [trace],
        "layout": go.Layout(
            height=700,
            width=700,
            font={"size": 16},
            margin={"t": 0, "b": 0, "l": 0, "r": 0},
            geo={
                "lataxis": {"range": [36.0, 71.0]},
                "lonaxis": {"range": [-10.0, 35.0]},
                "projection": {"type": "transverse mercator"},
                "resolution": 50,
                "showcoastlines": True,
                "showframe": True,
                "showcountries": True,
            },
        ),
    }
示例#19
0
def choro_map(d_frame, metric):
    state_data = d_frame[['State', 'State-abbreviation',
                          metric]].groupby(['State',
                                            'State-abbreviation']).sum()
    state_data = state_data.reset_index()
    locations = state_data['State-abbreviation'].values
    z_data = state_data[metric].values
    text = state_data.State.values
    ch_map = [
        go.Choropleth(locations=locations,
                      locationmode='USA-states',
                      z=z_data,
                      autocolorscale=False,
                      colorscale='YlOrRd',
                      colorbar={'tickprefix': '$'},
                      text=text)
    ]
    layout = go.Layout(height=240,
                       margin={
                           'l': 5,
                           'r': 5,
                           'b': 5,
                           't': 5
                       },
                       geo={
                           'scope': 'usa',
                           'projection': {
                               'type': 'albers usa'
                           },
                           'showframe': False
                       })
    return ch_map, layout
示例#20
0
def hu_run_select() -> 'html':
    the_region = request.form["the_region_selected"]  ## 取得用户交互输入
    print(the_region)  ## 检查用户输入, 在后台
    dfs = df.query("code=='{}'".format(
        the_region))  ## 使用df.query()方法. 按用户交互输入the_region过滤
    data_str = dfs.to_html()  # 数据产出dfs, 完成互动过滤

    fig = go.Figure(data=go.Choropleth(
        locations=dfs['code'],  # Spatial coordinates
        z=dfs['total'].astype(float),  # Data to be color-coded
        locationmode=
        'USA-states',  # set of locations match entries in `locations`
        colorscale='Reds',
        colorbar_title="Millions USD",
    ))

    fig.update_layout(
        title_text='美国大型枪击事件',
        geo_scope='usa',  # limite map scope to USA
    )

    fig.show()
    py.offline.plot(fig, filename="map_details.html", auto_open=False)

    with open("map_details.html", encoding="utf8",
              mode="r") as f:  # 把"map_details.html"當文字檔讀入成字符串
        plot_all = "".join(f.readlines())

    regions_available = regions_available_loaded  # 下拉选单有内容
    return render_template(
        'page_03_details.html',
        the_plot_all=plot_all,
        the_res=data_str,
        the_select_region=regions_available,
    )
示例#21
0
def update_figure(filter_choice, level_choice):
    average = all_options[filter_choice][0]
    text = all_options[filter_choice][1]
    title_text = all_options[filter_choice][2]
    dff = data_viz[data_viz['level'] == level_options[level_choice]]
    bar_title = all_options[filter_choice][4]

    return {
        'data': [
            go.Choropleth(
                colorscale=scl,
                autocolorscale=False,
                locations=dff['code'].unique(),
                z=[
                    '%.1f' % round(x, 1)
                    for x in dff[average].astype(float).unique()
                ],
                locationmode='USA-states',
                text=dff[text].unique(),
                marker=dict(line=dict(color='rgb(255,255,255)', width=2)),
                colorbar=dict(title=bar_title))
        ],
        'layout':
        go.Layout(
            title=title_text,
            geo=dict(scope='usa',
                     projection=dict(type='albers usa'),
                     showlakes=True,
                     lakecolor='rgb(255, 255, 255)'),
        )
    }
示例#22
0
def update_ds_map(disaster, year_value):
    df_count_year = disaster_nums[disaster_nums['incidentType'] == disaster].groupby(['state', 'yearofloss'])['incidentType'].count().reset_index()
    df_ds_year = df_count_year[df_count_year['yearofloss'].between(year_value[0], year_value[1])]
    dff_year_claims = df_ds_year.groupby('state')['incidentType'].sum()
    return {
        'data': [
            go.Choropleth(
                locations = dff_year_claims.index,
                z = dff_year_claims,
                locationmode = 'USA-states',
                colorscale = 'Blues'
            )
        ],
        'layout': go.Layout(
            title_text = str(disaster) + " Count by State (" + str(year_value[0]) + " - " + str(year_value[1]) + ")",
            geo_scope = 'usa',
            height=730,
            margin={
                'l': 25,
                'r': 0,
                'b': 25,
                't': 100,
            }
        )
    }
示例#23
0
def update_map(year_value, radio_item):

    year_value1 = year_value[0]
    year_value2 = year_value[1]

    category_meaning = {1: "successful", 2: "failed", 3: "canceled"}

    co = table[table['launched year'].between(year_value1,
                                              year_value2,
                                              inclusive=True)]
    co = co.drop(["launched year"], axis=1)
    co = co[co["state"] == category_meaning[radio_item]]
    co["ID"] = pd.to_numeric(co["ID"])
    co = co.drop("state", axis=1)
    new_co = co.groupby(["country"])['ID'].agg(sum)
    # percentage=table.groupby(["country"]).agg({"ID":'sum'})   new_table.div(country, level="country")*100
    new_co = pd.DataFrame(new_co)
    new_co = new_co.reset_index()
    sum_ = new_co["ID"].sum()
    new_co["percent"] = (new_co["ID"].div(sum_)).apply(lambda x: x * 100)

    fig_map = go.Figure(data=go.Choropleth(
        locations=new_co["country"],
        z=new_co["percent"],
        # text = table[(table["state"]=="failed") & (table['launched year']==2017)]['country'],
        colorscale='Blues',
        autocolorscale=False,
        reversescale=False,
        marker_line_color='darkgray',
        marker_line_width=0.5,
    ))

    return fig_map
示例#24
0
def getFig(value):
    fig = go.Figure(data=go.Choropleth(
        locations=df.loc[df["Year"] == value]["Country Code"],
        z=df.loc[df["Year"] == value]["Annual_CO2_Emissions"],
        text=df.loc[df["Year"] == value]["Country"],
        colorscale="RdYlBu",
        autocolorscale=False,
        reversescale=True,
        marker_line_color="darkgray",
        marker_line_width=0.5,
        colorbar_tickprefix="-",
        colorbar_title="CO2 Emissions<br>(tonnes)",
    ))

    fig.update_layout(
        title_text="Annual CO2 Emissions",
        geo=dict(showframe=False,
                 showcoastlines=False,
                 projection_type="equirectangular"),
        annotations=[
            dict(
                x=0.55,
                y=0.1,
                xref="paper",
                yref="paper",
                showarrow=False,
            )
        ],
    )

    return fig
示例#25
0
def update_chart(selection):
    if selection == 'dominant':
        df = df_dom
        df = df.merge(df_dep,
                      how="left",
                      left_on=["country", "dominant_source"],
                      right_on=["country", "label"])
        df["percent_dep"] = round(100 * df["dependence"], 0).astype("int")
        df.drop(df[df["dependence"] == 0].index.values, inplace=True)
        df["text"] = df["country"] + "<br>" + df[
            "dominant_source"] + " (" + df["percent_dep"].astype(
                "str") + "%" + " dependent" + ")"
        fig = go.Figure(data=go.Choropleth(
            locations=df['iso'],
            z=df['score'],
            text=df['text'],
            hoverinfo='text',
            showscale=False,
            colorscale=[[0, colors["color"][3]], [0.5, colors["color"][2]],
                        [1.0, colors["color"][1]]],
            marker_line_width=0.5,
            marker_line_color='white',
        ))
        fig.update_layout({
            "geo": {
                "projection_type": "natural earth",
                "lataxis_range": [-60, 85]
            }
        })
        fig.update_layout(l_map)
    else:
        fig = make_fig_1(selection)
    return fig
示例#26
0
def first():

    # data = [
    #     go.Bar(x=df['Country/Region'],y=df['Confirmed'])
    #
    # ]
    df_new['text'] = '<br>' + 'Confirmed :' + df_new['Confirmed'].astype(
        str) + '<br>' + 'Recovered :' + df_new['Recovered'].astype(
            str) + '<br>' + 'Deaths :' + df_new['Deaths'].astype(str)
    fig = go.Choropleth(
        locations=df_new.index,  # Spatial coordinates
        z=df_new['Confirmed'],  # Data to be color-coded
        locationmode=
        'country names',  # set of locations match entries in `locations`
        colorscale='Blues',
        showlegend=False,
        text=df_new['text'],
        hovertext=df_new.index,
        hovertemplate="Country:%{hovertext},%{text}",
        colorbar_title='Confirmed<br>Cases',
    )
    d4 = [fig]
    graphJSON_1 = json.dumps(d4, cls=plotly.utils.PlotlyJSONEncoder)

    schedule.every(600).minutes.do(get_data)
    return render_template('index.html', graphJSON=graphJSON_1)
示例#27
0
def update_map(var_selected, date_selected):
    if var_selected is None:
        raise PreventUpdate

    df = covid_data[[var_selected, 'day_of_year', 'date',
                     'country_name']].query(f"day_of_year=={date_selected}")

    map = go.Figure(
        data=go.Choropleth(locations=df['country_name'],
                           locationmode='country names',
                           z=np.log(df[var_selected]),
                           colorscale='Reds',
                           marker_line_color='black',
                           marker_line_width=0.5,
                           zmin=0,
                           zmax=max(np.log(covid_data[var_selected])),
                           text=df[var_selected],
                           hoverinfo='location+text'))
    map.update_layout(margin=dict(l=5, r=50, b=0, t=0, pad=2),
                      geo=dict(
                          showframe=False,
                          showcoastlines=True,
                          projection_type='equirectangular',
                      ))

    return map
示例#28
0
def update_choropleth(selector):
    """
    Updates the choropleth map in the "Browse" section based on user's metric choice.

    :param clickData: Selected metric (ie. MPI or GII).
    :return: A choropleth map.
    """
    if selector == "MPI":
        return {
            'data': [
                go.Choropleth(locations=totals_df['ISO'],
                              z=totals_df['MPI'].astype(float),
                              colorscale='Reds',
                              colorbar={
                                  "thickness": 10,
                                  "len": 0.65,
                                  "x": 0.95,
                                  "y": 0.5
                              },
                              text=totals_df['country'])
            ],
            'layout': {
                'height': 800,
                'width': 1300,
                'title': 'MPI by Country'
            }
        }
    else:
        return {
            'data': [
                go.Choropleth(locations=totals_df['ISO'],
                              z=totals_df['GII'].astype(float),
                              colorscale='Blues',
                              colorbar={
                                  "thickness": 10,
                                  "len": 0.65,
                                  "x": 0.85,
                                  "y": 0.5
                              },
                              text=totals_df['country'])
            ],
            'layout': {
                'height': 800,
                'width': 1300,
                'title': 'GII by Country'
            }
        }
示例#29
0
def us_plot():
    response = requests.get(us_url)
    df = pd.read_html(response.text, flavor=['bs4','html5lib'])
    state_code = ['NY','NJ','MA','CA','PA','IL','MI','FL','LA','CT','TX','GA','MD','OH','IN','WA','VA','CO','TN','NC','MO','RI','AZ','AL','MS','WI','SC','NV','IA','UT','KY','DC','DE','OK','MN','KS','AR','NM','OR','SD','NE','ID','NH','WV','ME','VT','ND','HI','WY','MT','AK']
    new_df = df[0].iloc[1:52]
    new_df['code'] = state_code

    fig = go.Figure(data=go.Choropleth(
        locations=new_df['code'], # Spatial coordinates
        z = new_df['TotalCases'].astype(int), # Data to be color-coded
        locationmode = 'USA-states', # set of locations match entries in `locations`
        colorscale = [[0, 'rgb(240, 239, 239)'],[0.1, 'rgb(222, 146, 139 )'],[0.2, 'rgb(222, 146, 139  )'],[0.3, 'rgb(207, 125, 117)'],[0.4, 'rgb(207, 125, 117)'],[0.5, 'rgb(207, 125, 117)'],[0.6, 'rgb(202, 114, 105   )'],[0.7, 'rgb(190, 102, 93   )'],[0.8, 'rgb(191, 87, 77  )'],[0.9, 'rgb(191, 73, 61 )'],[1, 'rgb(183, 53, 40)']],
        marker_line_color='white',
        colorbar_title = "Total Cases",

    ))

    fig.update_layout(
        geo_scope='usa' # limite map scope to USA
        
    )
  
    fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})
    
    div = fig.to_html(full_html=False)
    results = get_us_data()

    #donut chart 
    totalcase = []
    state_list = [0,1,2,3,4,5,6,7,8,9]
    for state in state_list:
        totalcase.append(new_df.iloc[state]['TotalCases'])
    other_states = df[0].iloc[11:52]
    sum = other_states.sum(axis=0,skipna = True)

    labels = ['New York','New Jersey','Massachusetts','Illinois','California','Pennsylvania','Michigan','Florida','Louisiana','Connecticut','Other States']
    values = [totalcase[0],totalcase[1] , totalcase[2], totalcase[3],totalcase[4],totalcase[5],totalcase[6],totalcase[7],totalcase[8],totalcase[9],sum['TotalCases']]

    # Use `hole` to create a donut-like pie chart
    fig_pie = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.5, marker={'colors': [
                     '#a43820',
                     '#364761',
                     '#627da8',
                     '#a87262',
                     '#61917f',
                     '#8fbaa5',
                     '#a1834d',
                     '#c9bbb3',
                     '#537a78',
                     '#364d4b',
                     '#dedcdc'
                     
                    ]
    },)])

    fig_pie.update_layout(margin={"r":0,"t":150,"l":0,"b":20})
    div_pie = fig_pie.to_html(full_html=False)
    div = fig.to_html(full_html=False)
    return render_template("us.html", results=results, plot_div=div,plot_div_pie=div_pie)
示例#30
0
def choropleth_plot():
    df = reviews["country"].replace("US", "United States").value_counts()
    
    plot([go.Choropleth(
            locationmode="country names",
            locations=df.index.values,
            text=df.index,
            z=df.values
            )])