Exemple #1
0
 def plot_earthquake_map(self, earthquakes: pd.DataFrame = None, faults: pd.DataFrame = None) -> go.Figure:
     figure = go.Figure()
     if earthquakes is None:
         earthquakes = self.earthquakes
     if faults is None:
         faults = self.faults
     for index, row in faults.iterrows():
         fault_line = go.Scattergeo(
             lat=row["latitudes"], lon=row["longitudes"], mode="lines",
             showlegend=False, line=dict(color="black", width=2), hoverinfo="skip"
         )
         figure.add_trace(fault_line)
     earthquake_points = go.Scattergeo(
         lat=earthquakes["latitude"], lon=earthquakes["longitude"], mode="markers",
         hoverinfo="text", hovertext=earthquakes["magnitude_hover_text"],
         showlegend=False,
         marker=dict(
             color=earthquakes["magnitude"],
             colorbar=dict(
                 title="Magnitude"
             )
         )
     )
     figure.add_trace(earthquake_points)
     figure.update_geos(
         projection_type="equirectangular",
         showland=True, landcolor="rgb(230, 145, 56)",
         showocean=True, oceancolor="rgb(0, 255, 255)", lakecolor="rgb(0, 255, 255)"
     )
     figure.update_layout(margin=dict(l=10, r=0, b=0, t=0, pad=0))
     config = dict(displayModeBar=False, displaylogo=False, scrollZoom=False, showTips=False, staticPlot=True)
     figure.show(config=config)
     return figure
Exemple #2
0
def create_plot(df, input_latlon):
    '''
    :param df: dataframe output for get_top5_distance
    :param input_latlon: output for get_input_latlon
    :return: html string
    '''
    fig = go.Figure()
    fig.add_trace(
        go.Scattergeo(lat=df['latitude'],
                      lon=df['longitude'],
                      hovertext=df['display'],
                      marker=dict(size=10)))

    fig.update_layout(template='plotly_dark', width=1100, height=600)
    fig.update_geos(showcountries=True)

    fig.add_trace(
        go.Scattergeo(lat=[input_latlon[0]],
                      lon=[input_latlon[1]],
                      hovertext="You are here",
                      marker=dict(size=10)))
    fig.update_layout(showlegend=False)

    div = fig.to_html()

    return div
Exemple #3
0
def plot_flight_network(df, base_dir, subset):
    dfC = df.set_index('FL_DATE')

    dfJuly = dfC.loc['2018-07', :].reset_index()

    dfRoutes = (dfJuly.groupby(['ORIGIN', 'DEST']).agg({
        'FL_DATE': 'count'
    }).rename(columns={
        'FL_DATE': 'ct'
    }).reset_index())

    dfPosO = (dfJuly.groupby('ORIGIN').agg({
        'ORIGIN_LAT': 'mean',
        'ORIGIN_LONG': 'mean'
    }).reset_index())
    dfPosD = (dfJuly.groupby('DEST').agg({
        'DEST_LAT': 'mean',
        'DEST_LONG': 'mean'
    }).reset_index())

    newRoutes = dfRoutes.merge(dfPosO, on='ORIGIN',
                               how='left').merge(dfPosD, on='DEST', how='left')

    fig = go.Figure()
    fig.add_trace(
        go.Scattergeo(locationmode='USA-states',
                      lon=dfPosO['ORIGIN_LONG'],
                      lat=dfPosO['ORIGIN_LAT'],
                      mode='markers',
                      marker=dict(size=2,
                                  color='rgb(255, 0, 0)',
                                  line=dict(width=3,
                                            color='rgba(68, 68, 68, 0)'))))

    for i in range(len(newRoutes)):
        fig.add_trace(
            go.Scattergeo(
                locationmode='USA-states',
                lon=[newRoutes['ORIGIN_LONG'][i], newRoutes['DEST_LONG'][i]],
                lat=[newRoutes['ORIGIN_LAT'][i], newRoutes['DEST_LAT'][i]],
                mode='lines',
                line=dict(width=1, color='rgb(252, 32, 128)'),
                opacity=float(newRoutes['ct'][i] / newRoutes['ct'].max())))

    fig.update_layout(
        title_text='July 2018 Flight Paths<br>(Hover for airport names)',
        showlegend=False,
        geo=dict(
            scope='north america',
            projection_type='azimuthal equal area',
            showland=True,
            landcolor='rgb(0, 0, 0)',
            countrycolor='rgb(100, 100, 100)',
        ),
    )

    path = os.path.join(base_dir, 'network.png')
    fig.show()
    pio.write_image(fig, path, format='png')
    def plotEncounterUserLocs(self, df_coords, saveTo, platform):
        #initialize a space for figure
        fig = go.Figure()

        #what to add as text parameter for markers
        keys = {'youtube': 'user_country', 'flickr_june_2019': 'user_location'}

        #add the user country markers
        fig.add_trace(
            go.Scattergeo(
                lon=df_coords['user_long'],
                lat=df_coords['user_lat'],
                hoverinfo='text',
                text=df_coords[
                    'user_country'],  #df_coords[keys[platform]], #df_coords['user_country'],
                mode='markers',
                marker=dict(size=4,
                            color='rgb(0, 255, 0)',
                            line=dict(width=3, color='rgba(65, 65, 65, 0)'))))

        #add the encounter location markers
        fig.add_trace(
            go.Scattergeo(
                lon=df_coords['enc_long'],
                lat=df_coords['enc_lat'],
                hoverinfo='text',
                text=df_coords[
                    'encounter_loc'],  #df_coords[keys[platform]], #df_coords['encounter_loc'],
                mode='markers',
                marker=dict(size=4,
                            color='rgb(255, 0, 0)',
                            line=dict(width=3, color='rgba(68, 68, 68, 0)'))))

        # #begin to add path traces from user country to encounter locations
        # flight_paths = []
        for i in range(len(df_coords)):
            fig.add_trace(
                go.Scattergeo(
                    lon=[df_coords['user_long'][i], df_coords['enc_long'][i]],
                    lat=[df_coords['user_lat'][i], df_coords['enc_lat'][i]],
                    mode='lines',
                    line=dict(width=1, color='blue')  #,
                    #             opacity = float(df_coords['cnt'][i]) / float(df_flight_paths['cnt'].max()),
                ))

        #update parameters of map figure to display
        fig.update_layout(
            title_text=saveTo + " sightings since 06.01.2019",
            showlegend=False,
            geo=dict(
                scope='world',
                projection_type='equirectangular',  #'azimuthal equal area',
                showland=True,
                landcolor='rgb(243, 243, 243)',
                countrycolor='rgb(204, 204, 204)',
            ),
        )
        print('showing')
        fig.show()
Exemple #5
0
def get_fig():
    df_airports = pd.read_csv(
        'https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
    df_airports.head()

    df_flight_paths = pd.read_csv(
        'https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
    df_flight_paths.head()

    fig = go.Figure()

    fig.add_trace(go.Scattergeo(
        locationmode='USA-states',
        lon=df_airports['long'],
        lat=df_airports['lat'],
        hoverinfo='text',
        text=df_airports['airport'],
        mode='markers',
        marker=dict(
            size=2,
            color='rgb(255, 0, 0)',
            line=dict(
                width=3,
                color='rgba(68, 68, 68, 0)'
            )
        )))

    for i in range(len(df_flight_paths)):
        fig.add_trace(
            go.Scattergeo(
                locationmode='USA-states',
                lon=[df_flight_paths['start_lon'][i],
                     df_flight_paths['end_lon'][i]],
                lat=[df_flight_paths['start_lat'][i],
                     df_flight_paths['end_lat'][i]],
                mode='lines',
                line=dict(width=1, color='red'),
                opacity=float(df_flight_paths['cnt'][i]) / float(df_flight_paths['cnt'].max()),
            )
        )

    fig.update_layout(
        title_text='Feb. 2011 American Airline flight paths<br>(Hover for airport names)',
        showlegend=False,
        geo=dict(
            scope='north america',
            projection_type='azimuthal equal area',
            showland=True,
            landcolor='rgb(243, 243, 243)',
            countrycolor='rgb(204, 204, 204)',
        ),
    )

    # fig.show()
    return fig
def railway_flow(places):
    '''
    
    plot the railway network departure from wuhan
    
    '''

    places = places.sort_values('cnt', ascending=False).reset_index(drop=True)

    fig = go.Figure()

    fig.add_trace(
        go.Scattergeo(locationmode='USA-states',
                      lon=places['long'],
                      lat=places['lat'],
                      hoverinfo='text',
                      text=places['name'],
                      mode='markers',
                      marker=dict(size=3,
                                  color='rgb(255, 0, 0)',
                                  line=dict(width=3,
                                            color='rgba(68, 68, 68, 0)'))))

    for i in range(len(places)):
        fig.add_trace(
            go.Scattergeo(lon=[114, places['long'][i]],
                          lat=[31, places['lat'][i]],
                          mode='lines',
                          hoverinfo='text',
                          text=places['name'][i],
                          line=dict(width=1, color='red'),
                          opacity=float(places['cnt'][i]) /
                          float(places['cnt'].max()),
                          name=places['name'][i]))

    fig.update_layout(title_text='Railways Departure From Wuhan',
                      geo=dict(
                          scope='asia',
                          projection_type='equirectangular',
                          showland=True,
                          landcolor='rgb(243, 243, 243)',
                          countrycolor='rgb(204, 204, 204)',
                      ),
                      margin={
                          'l': 0,
                          'r': 50,
                          't': 50,
                          'b': 0
                      })

    fig.show()

    return fig
Exemple #7
0
def plot_mapping_size_of_airport_wrt_their_delay_and_nb_of_flight(
        df_vols: pd.DataFrame, scale: int = 300):  # pragma: no cover
    scale = scale
    delays_by_airport_iso_alpha_gb = get_df_to_plot_the_airport_mapping_wrt_delay(
        df_vols)
    delays_by_airport_iso_alpha_gb[
        'text_nb_retard'] = delays_by_airport_iso_alpha_gb.apply(
            lambda x: 'Aeroport : ' + x['LIEU'] + '| Nombre de retard : ' +
            str(x["NB RETARD A L'ARRIVEE"]),
            axis=1)
    delays_by_airport_iso_alpha_gb[
        'text_nb_vol'] = delays_by_airport_iso_alpha_gb.apply(
            lambda x: 'Aeroport : ' + x['LIEU'] + '| Nombre de vols: ' + str(x[
                'NB VOLS']),
            axis=1)
    fig = go.Figure()

    fig.add_trace(
        go.Scattergeo(
            locationmode='USA-states',
            lon=delays_by_airport_iso_alpha_gb['LONGITUDE'],
            lat=delays_by_airport_iso_alpha_gb['LATITUDE'],
            text=delays_by_airport_iso_alpha_gb['text_nb_vol'],
            marker=dict(size=delays_by_airport_iso_alpha_gb['NB VOLS'] / scale,
                        line_color='rgb(0,0,255)',
                        line_width=0.5,
                        sizemode='area'),
            name='NB VOLS'))

    fig.add_trace(
        go.Scattergeo(
            locationmode='USA-states',
            lon=delays_by_airport_iso_alpha_gb['LONGITUDE'],
            lat=delays_by_airport_iso_alpha_gb['LATITUDE'],
            text=delays_by_airport_iso_alpha_gb['text_nb_retard'],
            marker=dict(
                size=delays_by_airport_iso_alpha_gb["NB RETARD A L'ARRIVEE"] /
                scale,
                line_color='rgb(0,0,255)',
                line_width=0.5,
                sizemode='area'),
            name="NB DE RETARD A L'ARRIVEE"))
    fig.update_layout(
        title=
        'Cartographie des aeroports en fonction de leur nombre de retard et nombre de vols',
    )

    st.plotly_chart(fig)
Exemple #8
0
def get_event_on_map(df,
                     column_name="si",
                     event_ids: List[int] = None,
                     scaling_factor: int = 5):
    filtered_df = df
    if event_ids:
        filtered_df = filtered_df[filtered_df["id"].isin(event_ids)]
    fig = go.Figure(
        data=go.Scattergeo(lon=filtered_df['lonMax'],
                           lat=filtered_df['latMax'],
                           text=filtered_df['si'],
                           mode='markers',
                           marker=dict(size=filtered_df['area'] *
                                       scaling_factor,
                                       opacity=0.8,
                                       reversescale=True,
                                       autocolorscale=False,
                                       colorscale='Viridis',
                                       cmin=0,
                                       color=filtered_df[column_name],
                                       cmax=filtered_df[column_name].max(),
                                       colorbar_title=f"{column_name}")))

    fig.update_layout(
        title=f'Heavy precipitation events ({column_name})',
        geo_scope='europe',
        geo=dict(
            # Add coordinates limits on a map
            lataxis=dict(range=[lat_min, lat_max]),
            lonaxis=dict(range=[long_min, long_max])))
    return fig
Exemple #9
0
def main():
    geolocator = Nominatim(user_agent= "marieclancy")
    jobs = get_jobs()
    jobs2 = get_data_from_stackoverflow()
    write_file(jobs)
    conn, cursor = open_db("jobs.sqlite")
    setup_db(cursor, conn)
    conn.commit()
    for job in jobs:
        insert_to_database(cursor, conn, job, geolocator)
    for job in jobs2:
        insert_to_database(cursor, conn, job, geolocator)

    df = pd.read_sql_query('SELECT * FROM JOBS', conn)
    df['text'] = df['location']

    fig = go.Figure(data=go.Scattergeo(
        lon=df['longitude'],
        lat=df['latitude'],
        text=df['text'],
        mode='markers',
    ))

    fig.update_layout(
        title='Marie Clancy project',
        geo_scope='world',
    )
    fig.show()
def cities_on_map(vk_elastic_db: es_client.VkDataDatabaseClient,
                  size=10,
                  is_need_active=False,
                  days_delta=20):
    scale = get_scale(
        get_count_of_users(vk_elastic_db, is_need_active, days_delta))
    countries = count_by_city_order_by_country(vk_elastic_db, size,
                                               is_need_active, days_delta)
    fig = go.Figure()

    for country in countries:
        names = [
            city['city'] + "<br>Users=" + str(city['count'])
            for city in country['cities']
        ]
        not_null_locations = []
        for city in country['cities']:
            if not city['location'] is None:
                not_null_locations.append(city['location'])
        lat = [location['latitude'] for location in not_null_locations]
        lon = [location['longitude'] for location in not_null_locations]
        count = [max(city['count'] / scale, 20) for city in country['cities']]
        color = get_random_color()
        fig.add_trace(
            go.Scattergeo(lon=lon,
                          lat=lat,
                          text=names,
                          marker=dict(size=count, color=color,
                                      sizemode='area'),
                          name=country['country']))
    fig.update_layout(geo=dict(showland=True, showcountries=True))
    plotly.offline.plot(fig, filename=f"{save_path}/cities_on_map.html")
    print(f"report: {save_path}/cities_on_map.html")
Exemple #11
0
def make_example_three_map(df):
    """ Return html code for plotly map of unique flight routes from an airport. """
    fig = go.Figure()

    # Add each unique flight route as a line on a globe map, with co-ordinates set
    for i in range(len(df)):
        fig.add_trace(
            go.Scattergeo(
                lon=[df["OriginLong"][i], df["DestLong"][i]],
                lat=[df["OriginLat"][i], df["DestLat"][i]],
                mode="lines+markers",
                line={"width": 3},
                text=df["OriginDest"][i],
                name=df["OriginDest"][i],
            ))
    fig.update_layout(
        geo={
            "showcountries": True,
            "projection": {
                "type": "orthographic"
            },  # try natural earth too
        },
        width=1500,
        height=700,  # Change figure size
    )
    return get_html(fig)
Exemple #12
0
def _graphs(local, dataset_name):

	if dataset_name == "Walker_Lake":

		df = dataset(dataset_name)

		#display(df.describe())

		fig = make_subplots(rows=2, cols=2,
			column_widths=[0.6, 0.4],row_heights=[0.4, 0.6],
			specs=[[{"type": "scattergeo", "rowspan": 2}, {"type": "scatter"}],
           [            None                    , {"type": "histogram"}]])

		fig.add_trace(go.Scattergeo(lat=pd.Series([38.695488]),
	                  lon=pd.Series([-118.71734]),
	                  mode="markers",
	                  marker=dict(size=30, opacity=0.8)), row=1, col=1)

		fig.add_trace(go.Histogram(x=df["Cu"], marker_color='#66CC66',opacity=0.75, name='Histogram Cu'),row=1, col=2)
		fig.add_trace(go.Scatter(x=df["X"], y=df["Y"], mode='markers', text =df["Cu"], marker=dict(color=df["Cu"], colorscale='Viridis')), row=2, col=2)

		fig.update_geos(
		projection_type="orthographic",
	    lakecolor="LightBlue",
	    landcolor="white",
    	oceancolor="MidnightBlue",
    	showocean=True)

		fig.update_layout(
	    template="plotly_white",
	    margin=dict(r=10, t=25, b=40, l=60))

		fig.show()
Exemple #13
0
def make_edge_trace(df, from_selection=True):
    # edge stats: n 2k, min 1, max 7k, Q75 11, mean 45, median 3,
    if not from_selection:
        df = df[df['edge_count'] > 10]
        # after filter: n 500, min 11, max 7k, mean 161, median 30, Q75 82

    # todo: make a decent mapper
    def width_mapper(x):
        if x > 1000:
            return 15
        elif x > 500:
            return 8
        elif x > 100:
            return 4
        elif x > 50:
            return 2
        else:
            return 1

    edge_traces = []
    for index, row in df.iterrows():
        edge_trace = go.Scattergeo(
            locations=row['zipped'],
            mode='lines',
            line={'color': 'rgba(191, 178, 63, 0.2)', 'width': width_mapper(row['edge_count'])},
        )
        edge_traces.append(edge_trace)
    return edge_traces
Exemple #14
0
def world_map(view, date_index):
    '''
	creates the lower-left chart (map)
	'''
    if view == 'United States':
        scope = 'usa'
        projection_type = 'albers usa'
        df = df_us_counties
        # df = df[df['date'] == df['date'].unique()[date_index]]
        df = df.rename(columns={'key': 'Country/Region'})
        sizeref = 3
    else:
        df = data
        df = world_map_processing(df, date_index)
        scope = 'world'
        projection_type = 'natural earth',
        sizeref = 10
    return {
      'data': [
       go.Scattergeo(
        lon = df['Longitude'],
        lat = df['Latitude'],
        text = df['Country/Region'] + ': ' +\
         ['{:,}'.format(i) for i in df['Confirmed']] +\
         ' total cases, ' + df['percentage'] +\
         '% from previous week',
        hoverinfo = 'text',
        mode = 'markers',
        marker = dict(reversescale = False,
         autocolorscale = False,
         symbol = 'circle',
         size = np.sqrt(df['Confirmed']),
         sizeref = sizeref,
         sizemin = 0,
         line = dict(width=.5, color='rgba(0, 0, 0)'),
         colorscale = 'Reds',
         cmin = 0,
         color = df['share_of_last_week'],
         cmax = 100,
         colorbar = dict(
          title = "Percentage of<br>cases occurring in<br>the previous week",
          thickness = 30)
         )
        )
      ],
      'layout': go.Layout(
       title ='Number of Cumulative Confirmed Cases (size of marker)<br>and Share of New Cases from the Previous Week (color)',
       geo=dict(scope=scope,
         projection_type=projection_type,
         showland = True,
         landcolor = "rgb(100, 125, 100)",
         showocean = True,
         oceancolor = "rgb(80, 150, 250)",
         showcountries=True,
         showlakes=True),
       font=dict(color=colors['text']),
       paper_bgcolor=colors['bg'],
       plot_bgcolor=colors['background']
      )
     }
Exemple #15
0
def draw_infection_map(df, day):
    df = df[['Province/State', 'Country/Region', 'Lat', 'Long', day]].copy()
    df = df[df[day] != 0]
    map_trace = go.Scattergeo(
        lat=df['Lat'],
        lon=df['Long'],
        marker=dict(
            size=df[day]/50,
            sizemode='area',
            color='#D9534F'
        )
    )

    layout = go.Layout(
        margin=dict(l=0, r=0, t=0, b=0),
        geo=dict(
            landcolor='#ABB6C2',
            showocean=True,
            oceancolor='#4E5D6C',
            showcountries=True,
            showframe=False,
            framewidth=0,
            bgcolor='#2B3E50'
        ),
        paper_bgcolor='#4E5D6C',
        transition=dict(
            duration=500,
            easing='cubic-in-out'
        )
    )

    fig = go.Figure(data=[map_trace], layout=layout)
    return fig
Exemple #16
0
def bubbleplot(df, names, colors, markerSize):
    fig = go.Figure()

    for i in range(len(df)):
        df_sub = df[i]
        fig.add_trace(go.Scattergeo(
            locationmode = "ISO-3",
            lat = df_sub['Latitude'],
            lon = df_sub['Longitude'],
            text = df_sub['Code'],
            marker = dict(
                size = markerSize[i],
                color = colors[i],
                line_color='rgb(40,40,40)',
                line_width=0.5,
                sizemode = 'area'),
            name = names[i]))
        
    fig.update_layout(
        title_text = "Airports, Starbucks and <br>old companies in Europe",
        showlegend = True,
        geo = dict(
            scope = 'europe',
            landcolor = 'rgb(217, 217, 217)',
        )
    )

    fig.write_html("OUTPUT/bubbleplot.html")
    return fig
Exemple #17
0
def createFigure(myDataFrame):
    myDataFrame['text'] = myDataFrame['case'] + \
        '<br>Total Victims: ' + (myDataFrame['total_victims']).astype(str)
    limits = [(0, 6), (7, 15), (16, 605)]
    colors = ["royalblue", "crimson", "lightseagreen"]

    fig = go.Figure()

    fig.add_trace(
        go.Scattergeo(locationmode='USA-states',
                      lon=myDataFrame['longitude'],
                      lat=myDataFrame['latitude'],
                      text=myDataFrame['text'],
                      marker=dict(size=myDataFrame['total_victims'],
                                  color=colors[0],
                                  line_color='rgb(40,40,40)',
                                  line_width=0.5,
                                  sizemode='area'),
                      name="mass shootings by location and number of victims"))

    fig.update_layout(
        title_text=
        'Mass Shootings Corresponding to Total Victims Across the United States',
        showlegend=True,
        geo=dict(
            scope='usa',
            landcolor='rgb(217, 217, 217)',
        ),
    )

    py.plot(fig, filename="map_of_mass_shootings.html", auto_open=True)

    fig.show()
def geo_scatter():
    colors = ['rgb(33, 75, 99)','rgb(79, 129, 102)','rgb(151, 179, 100)','rgb(175, 49, 35)','rgb(36, 73, 147)']
    fig = go.Figure()
    distinct_op = get_distinct_value('operator')
    for i in range(len(distinct_op)):
        op = distinct_op[i][0]
        df = query_rows('operator', op)
        fig.add_trace(go.Scattergeo(
            locationmode = 'USA-states',
            lon = df['lo_lng'],
            lat = df['lo_lat'],
            text = "vending machine ID: " + df['vm_id'],
            marker = dict(
                color=colors[i],
                opacity=0.8,
                size=18,
            ),
            name = moniker_name_converter(op),
            hoverinfo='text+name'
        ))
    fig.update_layout(
        autosize=True,
        geo = dict(
            scope = 'usa',
            landcolor = '#e3e1cf',
        ),
        legend_orientation="h",
        margin = go.layout.Margin(l=10, r=10, t=10, b=10),
        showlegend = True,
    )
    return dcc.Graph(id='geo-scatter', figure=fig)
Exemple #19
0
def update_corona_map(date):
    """
    Return geo scatterplot map for specified date on app callback.
    """
    master_subset = master[master['date_time'] == date]
    fig = go.Figure(
        go.Scattergeo(
            lon=master_subset['Long'],
            lat=master_subset['Lat'],
            mode='markers',
            customdata=np.stack(
                (master_subset['Confirmed'], master_subset['Deaths'],
                 master_subset['Recovered'], master_subset['Province/State']),
                axis=-1),
            marker=dict(size=master_subset['Confirmed_Size'] * 1.75,
                        color=master_subset['Deaths_Color'],
                        colorscale=scl,
                        colorbar_title='Deaths (Natural Log Scale)'),
            hovertemplate='<b>%{customdata[3]}</b><br><br>' +
            '<b>Confirmed Cases</b>: %{customdata[0]}\
                                    <br>' +
            '<b>Deaths</b>: %{customdata[1]}<br>' +
            '<b>Recovered</b>: %{customdata[2]}'))
    fig.update_geos(showcountries=True,
                    projection_type='natural earth',
                    landcolor='#cccccc',
                    showocean=True,
                    oceancolor='#a8d7ff')
    fig.update_layout(height=300, margin={"r": 0, "t": 0, "l": 0, "b": 0})
    return fig
Exemple #20
0
def add_trace(fig,
              cities_dict,
              city_1,
              city_2,
              lon=lambda x: x["lon"],
              lat=lambda x: x["lat"]):

    city_1_lon = lon(cities_dict[city_1])
    city_1_lat = lat(cities_dict[city_1])
    city_2_lon = lon(cities_dict[city_2])
    city_2_lat = lat(cities_dict[city_2])

    if (city_1_lon < 0 < city_2_lon and np.abs(city_1_lon) > 90
            and np.abs(city_2_lon) > 90):
        city_1_lon = city_1_lon + 360
    elif (city_1_lon > 0 > city_2_lon and np.abs(city_1_lon) > 90
          and np.abs(city_2_lon) > 90):
        city_2_lon = city_2_lon + 360

    fig.add_trace(
        go.Scattergeo(
            locationmode="USA-states",
            mode="lines",
            lon=[city_1_lon, city_2_lon],
            lat=[city_1_lat, city_2_lat],
            marker={"size": 10},
            line=dict(width=1, color="red"),
        ))
Exemple #21
0
def us_map(metric, Data):
    fig = go.Figure(data=go.Scattergeo(
        #locationmode = 'USA-states',
        lon=Data['Long_'],
        lat=Data['Lat'],
        text=Data['text'],
        mode='markers',
        marker=dict(
            size=4,
            opacity=0.95,
            reversescale=True,
            autocolorscale=False,
            symbol='square',
            line=dict(width=1, color='rgba(102, 102, 102)'),
            colorscale='Electric',  #scl, #'Blues',
            color=Data[metric],
            cmin=np.percentile(Data[metric], [1])[0],
            cmax=np.percentile(Data[metric], [99.5])[0],
            colorbar_title="{}".format(metric))))
    fig.update_layout(
        title='Covid-19 US County Map, {} (Hover for status)'.format(
            str(date_max)[:10]),
        #geo_scope='usa'
        autosize=False,
        width=900,
        height=600,
        geo=dict(scope='usa',
                 projection_type='albers usa',
                 showland=True,
                 landcolor="rgb(250, 250, 250)",
                 subunitcolor="rgb(217, 217, 217)",
                 countrycolor="rgb(217, 217, 217)",
                 countrywidth=0.5,
                 subunitwidth=0.5))
    return fig
Exemple #22
0
def generateSchoolMap(covid):
    # load data first time only

    schoollist = pullpublicschool(covid)
    myfile = open("schools.json", "w")
    myfile.write(schoollist.decode("utf-8"))

    df = pd.read_json(open("schools.json", "r", encoding="utf8"), lines=True)

    # make the map
    fig = go.Figure(data=go.Scattergeo(
        lon=df['lon'][0],
        lat=df['lat'][0],
        text=df['name'][0],
        mode='markers',
    ))

    fig.update_layout(
        title='Public schools across America',
        geo_scope='usa',
    )

    #fig.write_html("temp1.html", auto_open=True)

    return fig
Exemple #23
0
def map_plot(long, lat, names, search_city, food_type):
    fig = go.Figure(data=go.Scattergeo(
        locationmode='USA-states',
        lon=long,
        lat=lat,
        text=names,
        mode='markers',
        marker=dict(size=8,
                    opacity=.8,
                    symbol='circle',
                    line=dict(width=1, color='rgba(102, 102, 102)'),
                    colorscale='Blues',
                    colorbar_title="Restaurants by Food Type")))

    fig.update_layout(
        title=
        "Popular restaurants based on cuisin <br> (Hover for restaurant names)",
        geo=dict(scope='usa',
                 projection_type='albers usa',
                 showland=True,
                 landcolor="rgb(250, 250, 250)",
                 subunitcolor="rgb(217, 217, 217)",
                 countrycolor="rgb(217, 217, 217)",
                 countrywidth=0.5,
                 subunitwidth=0.5),
    )
    fig.show()
Exemple #24
0
def draw_map(papers: List[Paper]):
    """" Draw a bubble map with countries' paper amount showing"""

    sizeref = 2 * 36 / (70 ** 2)
    df = pd.read_csv("../gradu/material/data/country_data.csv")
    df["text"] = df["count"].astype(str)
    fig = go.Figure(
        data=go.Scattergeo(
            lon=df["lon"],
            lat=df["lat"],
            text=df["text"],
            mode="markers+text",
            marker=dict(
                color=df["count"],
                colorscale="Delta",
                size=df["count"],
                sizemode="area",
                sizeref=sizeref,
                sizemin=7,
            ),
            textfont=dict(family="sans serif", color="white"),
        )
    )
    fig.update_geos(projection_type="natural earth")
    fig.show()
def choropleth(df, var, plot_target, target=[]):
  if plot_target:
    values = target
  else:
    values = df[var]
  X = df.X; Y = df.Y
  data = go.Scattergeo(
        lon = X,
        lat = Y,
        text = values ,
        mode = 'markers',
        marker_color = values,
        marker = dict(
            size = 8,
            opacity = 0.8,
            reversescale = True,
            autocolorscale = False,
            colorscale = 'hot',
            cmin = 0,
            color = values,
            cmax = values.max(),
            colorbar_title=var)
          )
  fig = go.Figure(data=data, layout=layout)
  fig.update_layout(
      width=800, height=800,
       geo_scope='africa'
     )
  return fig
def chinaMap_deaths():

    ch_latest = ds.ch_latest

    ch_latest_grouped = ch_latest.groupby(['Province/State', 'Lat', 'Long'
                                           ])['Confirmed', 'Deaths',
                                              'Recovered',
                                              'Active'].sum().reset_index()
    ch_latest_grouped['desc'] = ch_latest_grouped.agg(
        '{0[Province/State]} : {0[Deaths]}'.format, axis=1)
    ch_latest_grouped['size'] = ch_latest_grouped['Deaths'].pow(0.9)

    cases = []
    cases.append(
        go.Scattergeo(
            lon=ch_latest_grouped['Long'],
            lat=ch_latest_grouped['Lat'],
            hovertext=ch_latest_grouped['desc'],
            marker=dict(size=ch_latest_grouped['size'],
                        color='red',
                        line_color='rgb(40,40,40)',
                        line_width=0.5,
                        sizemode='area'),
        ))

    layout = go.Layout(
        title="Peta China dengan Kasus Meninggal",
        geo=dict(resolution=50,
                 bgcolor='rgba(0,0,0,0)',
                 scope='asia',
                 showframe=False,
                 showcoastlines=True,
                 showland=True,
                 landcolor="#989898",
                 countrycolor="rgb(255, 255, 255)",
                 coastlinecolor="rgb(255, 255, 255)",
                 projection=dict(type='mercator', scale=2),
                 center=dict(lon=98.044117, lat=36.058394)),
        font={
            "size": 9,
            "color": "White"
        },
        titlefont={
            "size": 20,
            "color": "White"
        },
        paper_bgcolor='#303030 ',
        plot_bgcolor='#303030 ',
        width=620,
        height=500,
    )

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

    plot_div = plot(fig,
                    image_width='100%',
                    image_height='100%',
                    output_type='div',
                    include_plotlyjs=False)
    return plot_div
Exemple #27
0
def get_BubbleMap(role):
    '''
    This function produces a Bubble map  of job Occurence by city
    '''
    ##Separating African Data from US data
    if (role == "Data Analyst") or (role == "Network Engineer"):
        mapdata = mapdata2
        scp = "africa"  ## setting the plot scope
        fct = 1  ## setting the magnification factor
    else:
        mapdata = mapdata1
        scp = "usa"  ## setting the plot scope
        fct = 15  ## setting the magnification factor
    mapdf = mapdata[mapdata["Role"] == role]  ## Filtering location Data
    fig = go.Figure()  ##Initializing the figure
    fig = fig.add_trace(
        go.Scattergeo(locationmode='USA-states',
                      lon=mapdf['longitude'],
                      lat=mapdf['latitude'],
                      text=mapdf['City'],
                      marker=dict(size=mapdf['Count'] * fct, color="#FF1E91")))
    fig = fig.update_layout(showlegend=False,
                            geo=dict(
                                scope=scp,
                                landcolor='rgb(217, 217, 217)',
                            ),
                            margin=go.layout.Margin(l=0, r=0, b=0, t=0, pad=4),
                            plot_bgcolor="#ffffff",
                            paper_bgcolor="#ffffff")
    return fig
Exemple #28
0
def home_page():
    global tweets
    global sentiments
    global hashtag_counts
    global word_counts
    global geodata
    global graphJSON
    global jqCloud_word_count

    print("Tweets variable", file=sys.stderr)
    print(tweets, file=sys.stderr)
    print("word count variable", file=sys.stderr)
    print(word_counts, file=sys.stderr)
    print("hashtag variable", file=sys.stderr)
    print(hashtag_counts, file=sys.stderr)
    print(hashtag_counts['words'], file=sys.stderr)
    
    wc = dict(zip(hashtag_counts['words'], hashtag_counts['counts']))
    jqCloud_word_count = [{'text': word, 'weight': count} for word, count in wc.items()]

    trace = go.Scattergeo(lon = geodata['longitude'],
                          lat = geodata['latitude'],
                          mode = 'markers')
    data = [trace]
    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)

    return render_template(
            'index.html',
            tweets=zip(tweets['users'], tweets['text'], tweets['id']),
            sentiments=sentiments,
            wordcounts=word_counts,
            jqCloud_word_count=jqCloud_word_count,
            graphJSON=graphJSON)
def bubble_map(confirmed, date):
    '''
    plot the map how many were confirmed in China for each province on specific date
    '''

    #assert statement
    assert type(confirmed) == pd.core.frame.DataFrame
    assert isinstance(date, str)

    #set the confirmed cases to 7000 for Hubei province, of which the index is 12
    confirmed.at[12, date] = 7000

    #set limits and corresponding colors and the bubble area scale
    limits = [(2000, 100000), (900, 2000), (300, 900), (100, 300), (0, 100)]
    colors = [
        "crimson",
        "orange",
        "yellow",
        "lightyellow",
        "lightgrey",
    ]
    scale = 2

    fig = go.Figure()

    #add trace for each province within limits
    for i in range(len(limits)):
        lim = limits[i]
        df_sub = confirmed.loc[confirmed[date] < lim[1]]
        fig.add_trace(
            go.Scattergeo(
                locationmode='USA-states',
                lon=df_sub['Long'],
                lat=df_sub['Lat'],
                hoverinfo='text',
                text=df_sub[['Province/State', date]],
                #text = df_sub['text'],
                marker=dict(size=df_sub[date] / scale,
                            color=colors[i],
                            line_color='rgb(40,40,40)',
                            line_width=0.5,
                            sizemode='area'),
                name='{0} - {1}'.format(lim[0], lim[1])))

    #update the layout
    fig.update_layout(title_text=date,
                      showlegend=True,
                      geo=dict(scope='asia', landcolor='rgb(243, 243, 243)'),
                      margin={
                          'l': 50,
                          'r': 50,
                          't': 50,
                          'b': 0
                      })

    fig.show()

    py.offline.plot(fig, filename='plots/china_confirmed_case_map.html')

    return confirmed
Exemple #30
0
    def plot(self):
        states = self.get_state_map_data()
        map = plotgraph.Figure(layout=map_layout)
        hover_txt = states.States.astype(str) + "<br>&#931;: " + states.Sigma.astype(str) + \
                    "<br>Rate of Transmision: "+ states.Rt.astype(str) + \
                    "<br>Population: " + states.Population.apply(lambda x : "{:,}".format(x)).astype(str)

        scatter = plotgraph.Scattergeo(
            locationmode='country names',
            lon=states.Longitude,
            lat=states.Latitude,
            hoverinfo='text',
            text=states.States,
            hovertext=hover_txt,
            mode='markers',
            marker={'colorscale': ['Green', 'Orange', 'Red'], "showscale":True, 'size': self.__squash(states.Sigma), 'color': states.Rt})

        map.update_layout(
            xaxis =  { 'showgrid': False,'zeroline': False,'visible' : False},
            yaxis = {'showgrid': False,'zeroline': False,'visible' : False})

        map.add_trace(scatter)
        day_count = (dt.now() - states["Reported"].min()).days

        return map