def data_load(data):

    # ----------------------
    # Load
    # ----------------------

    # Define Map

    def updateMap(data, limit1, limit2, limit3, limit4, condition,
                  construction):

        houses = data[(data['sqft_living'] >= limit1)
                      & (data['bathrooms'] >= limit2) &
                      (data['price'] <= limit3) &
                      (data['sqft_basement'] <= limit4) &
                      (data['condition'] >= condition) &
                      (data['yr_built'] <= construction)][[
                          'id', 'lat', 'long', 'sqft_living', 'bathrooms',
                          'price', 'sqft_basement', 'condition', 'yr_built'
                      ]]

    # plot map
    st.title('House Rocket Map')
    is_check = st.checkbox('Display Map')

    living_room_min = int(data['sqft_living'].min())
    living_room_max = int(data['sqft_living'].max())
    bedroom_min = int(data['bedrooms'].min())
    bedroom_max = int(data['bathrooms'].max())
    price_min = int(data['price'].min())
    price_max = int(data['price'].max())
    basement_size_min = int(data['sqft_basement'].min())
    basement_size_max = int(data['sqft_basement'].max())
    house_condition_min = int(data['condition'].min())
    house_condition_max = int(data['condition'].max())
    year_built_min = int(data['yr_built'].min())
    year_built_max = int(data['yr_built'].max())
    # waterview = str(data['waterfront'])

    living_room = st.slider('Living room size',
                            min_value=living_room_min,
                            max_value=living_room_max,
                            value=6000,
                            step=100)
    bedroom = st.slider('Number of bedrooms',
                        min_value=bedroom_min,
                        max_value=bedroom_max,
                        value=3,
                        step=1)
    price = st.slider('House price',
                      min_value=price_min,
                      max_value=price_max,
                      value=1000000,
                      step=5000)
    basement_size = st.slider('Basement size',
                              min_value=basement_size_min,
                              max_value=basement_size_max,
                              value=1000,
                              step=10)
    house_condition = st.slider('House condition',
                                min_value=house_condition_min,
                                max_value=house_condition_max,
                                value=3,
                                step=1)

    year_built = st.slider('Year built',
                           min_value=year_built_min,
                           max_value=year_built_max,
                           value=2000,
                           step=1)

    waterview = st.selectbox('Water View', options=['Yes', 'No'], index=0)

    if is_check:
        # select rows
        houses = data[(data['sqft_living'] < living_room)
                      & (data['bedrooms'] < bedroom) & (data['price'] < price)
                      & (data['sqft_basement'] < basement_size) &
                      (data['condition'] <= house_condition) &
                      (data['yr_built'] <= year_built) &
                      (data['waterfront'] == waterview)][[
                          'id', 'lat', 'long', 'price'
                      ]]
        # st.dataframe(houses)
        fig = px.scatter_mapbox(
            houses,
            lat='lat',
            lon='long',
            # color = 'bathrooms',
            size='price',
            color_continuous_scale=px.colors.cyclical.IceFire,
            size_max=15,
            zoom=10)

        fig.update_layout(mapbox_style='open-street-map')
        fig.update_layout(height=600,
                          margin={
                              'r': 0,
                              't': 0,
                              'l': 0,
                              'b': 0,
                          })
        st.plotly_chart(fig)
Ejemplo n.º 2
0
def update_app_ui2(month_value, day_value, region_value, country_value,
                   state_value, city_value, attack_value, year_value):

    if (region_value != None):
        df1 = pd.DataFrame()
        dfnew = pd.DataFrame()
        n = [x for x in range(year_value[0], year_value[1] + 1)]
        for i in n:
            df2 = pd.DataFrame(df[df['iyear'] == i])
            df1 = df1.append(df2)

        df3 = pd.DataFrame(df[df['region_txt'] == (region_value)])
        df1 = df1.merge(df3)
        dfnew = df1
        print(df1)

        if (country_value != None):
            dfnew = df1
            dfc = pd.DataFrame(df[df['country_txt'] == (country_value)])
            df1 = df1.merge(dfc)

            if (month_value != None):
                dfnew = df1
                dfm = pd.DataFrame(df[df['imonth'].isin(month_value)])
                df1 = df1.merge(dfm)

            if (day_value != None):
                dfnew = df1
                dfd = pd.DataFrame(df[df['iday'].isin(day_value)])
                df1 = df1.merge(dfd)

            if (state_value != None):
                dfnew = df1
                dfs = pd.DataFrame(df[df['provstate'].isin(state_value)])
                df1 = df1.merge(dfs)

            if (city_value != None):
                dfnew = df1
                dfy = pd.DataFrame(df[df['city'].isin(city_value)])
                df1 = df1.merge(dfy)

            if (attack_value != None):
                dfnew = df1
                dfa = pd.DataFrame(
                    df[df['attacktype1_txt'].isin(attack_value)])
                df1 = df1.merge(dfa)

    if df1.empty:
        value = 'No Results Found'
        fig = px.scatter_mapbox(dfnew,
                                lat=dfnew["latitude"],
                                lon=dfnew["longitude"],
                                hover_name=dfnew["city"],
                                hover_data=[
                                    'region_txt', 'country_txt', 'provstate',
                                    'city', 'attacktype1_txt', 'nkill',
                                    'imonth', 'iday'
                                ],
                                color='attacktype1_txt',
                                zoom=2,
                                height=500)
        fig.update_layout(mapbox_style="open-street-map")

        fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    else:
        value = 'Results Found'
        print('the df1 in month is', df1)
        fig = px.scatter_mapbox(df1,
                                lat=df1["latitude"],
                                lon=df1["longitude"],
                                hover_name=df1["city"],
                                hover_data=[
                                    'region_txt', 'country_txt', 'provstate',
                                    'city', 'attacktype1_txt', 'nkill',
                                    'imonth', 'iday'
                                ],
                                color='attacktype1_txt',
                                zoom=2,
                                height=500)
        fig.update_layout(mapbox_style="open-street-map")

        fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

    return fig, value
def update_app_ui(
    Tabs,
    subtabs2,
    month_value,
    date_value,
    region_value,
    country_value,
    state_value,
    city_value,
    attack_value,
    year_value,
    chart_dp_value,
    search,
    chart_year_value,
):
    fig = None
    if (Tabs == "Map"):
        print("Data Type of month value = ", str(type(month_value)))
        print("Data of month value = ", month_value)

        print("Data Type of Day value = ", str(type(date_value)))
        print("Data of Day value = ", date_value)

        print("Data Type of region value = ", str(type(region_value)))
        print("Data of region value = ", region_value)

        print("Data Type of country value = ", str(type(country_value)))
        print("Data of country value = ", country_value)

        print("Data Type of state value = ", str(type(state_value)))
        print("Data of state value = ", state_value)

        print("Data Type of city value = ", str(type(city_value)))
        print("Data of city value = ", city_value)

        print("Data Type of Attack value = ", str(type(attack_value)))
        print("Data of Attack value = ", attack_value)

        print("Data Type of year value = ", str(type(year_value)))
        print("Data of year value = ", year_value)
        # year_filter
        year_range = range(year_value[0], year_value[1] + 1)
        new_df = df[df["iyear"].isin(year_range)]
        # month_filter
        if month_value == [] or month_value is None:
            pass
        else:
            if date_value == [] or date_value is None:
                new_df = new_df[new_df["imonth"].isin(month_value)]
            else:
                new_df = new_df[new_df["imonth"].isin(month_value)
                                & (new_df["iday"].isin(date_value))]
        # region, country, state, city filter
        if region_value == [] or region_value is None:
            pass
        else:
            if country_value == [] or country_value is None:
                new_df = new_df[new_df["region_txt"].isin(region_value)]
            else:
                if state_value == [] or state_value is None:
                    new_df = new_df[
                        (new_df["region_txt"].isin(region_value))
                        & (new_df["country_txt"].isin(country_value))]
                else:
                    if city_value == [] or city_value is None:
                        new_df = new_df[
                            (new_df["region_txt"].isin(region_value))
                            & (new_df["country_txt"].isin(country_value)) &
                            (new_df["provstate"].isin(state_value))]
                    else:
                        new_df = new_df[
                            (new_df["region_txt"].isin(region_value))
                            & (new_df["country_txt"].isin(country_value)) &
                            (new_df["provstate"].isin(state_value)) &
                            (new_df["city"].isin(city_value))]

        if attack_value == [] or attack_value is None:
            pass
        else:
            new_df = new_df[new_df["attacktype1_txt"].isin(attack_value)]

        if new_df.shape[0]:
            pass
        else:
            new_df = pd.DataFrame(columns=[
                'iyear', 'imonth', 'iday', 'country_txt', 'region_txt',
                'provstate', 'city', 'latitude', 'longitude',
                'attacktype1_txt', 'nkill'
            ])

            new_df.loc[0] = [
                0, 0, 0, None, None, None, None, None, None, None, None
            ]

        mapFigure = px.scatter_mapbox(new_df,
                                      lat="latitude",
                                      lon="longitude",
                                      color="attacktype1_txt",
                                      hover_name="city",
                                      hover_data=[
                                          "region_txt", "country_txt",
                                          "provstate", "city",
                                          "attacktype1_txt", "nkill", "iyear",
                                          "imonth", "iday"
                                      ],
                                      zoom=1)
        mapFigure.update_layout(
            mapbox_style="stamen-toner",
            autosize=True,
            margin=dict(l=0, r=0, t=25, b=20),
        )

        fig = mapFigure

    elif (Tabs == "Chart"):
        fig = None
        chart_df = None
        year_range_chart = range(chart_year_value[0], chart_year_value[1] + 1)
        chart_df = df[df["iyear"].isin(year_range_chart)]

        if subtabs2 == "WorldChart":
            pass
        elif subtabs2 == "IndiaChart":
            chart_df = chart_df[(chart_df["region_txt"] == "South Asia")
                                & (chart_df["country_txt"] == "India")]

        if chart_dp_value is not None:
            if search is not None:
                chart_df = chart_df.groupby(
                    "iyear")[chart_dp_value].value_counts().reset_index(
                        name="count")
                chart_df = chart_df[chart_df[chart_dp_value].str.contains(
                    search, case=False)]
            else:
                chart_df = chart_df.groupby(
                    "iyear")[chart_dp_value].value_counts().reset_index(
                        name="count")
        else:
            raise PreventUpdate

        if chart_df.shape[0]:
            pass
        else:
            chart_df = pd.DataFrame(columns=['iyear', 'count', chart_dp_value])
            chart_df.loc[0] = [0, 0, "No data"]

        fig = px.area(chart_df, x="iyear", y="count", color=chart_dp_value)

    return dcc.Graph(figure=fig)
Ejemplo n.º 4
0
#Using MapBox (via Plotly plugin) for city-focused geo visuals. Default Plotly maps are only available at more macro levels (globe, country)

MBToken = 'pk.eyJ1Ijoic2NvaGVuZGUiLCJhIjoiY2szemMxczZoMXJhajNrcGRsM3cxdGdibiJ9.2oazpPgLvgJGF9EBOYa9Wg'
px.set_mapbox_access_token(MBToken)

specText = 'Below is a map of all schools marked as "Specialized", broken up by borough (color). The size of the circle \
denotes enrollment size. The four largest circles are the oldest specialized schools: Stuyvesant, Bronx Science and Brooklyn Tech, \
which specialize in STEM; and Laguardia, which specializes in the arts). These are also the oldest specialized schools. The \
smaller circles are relative newcomers to the specialized admissions process, and show that an expansion of the system is \
already underway'

specFig = px.scatter_mapbox(specSchools.dropna(),
                            lat="latitude",
                            lon="longitude",
                            color="borough",
                            size="total_students",
                            text="school_name",
                            hover_name="school_name",
                            hover_data=["neighborhood"],
                            size_max=15,
                            zoom=9)

intText = 'Taking a look at the breakdown in popular interests in non-specialized schools. Science/Tech takes up a lot of \
space, but there is a lot of interest in Humanities. As of now, there are no schools which specialize in social sciences.'

intFig = go.Figure(
    data=[go.Pie(labels=dfg3['interests'], values=dfg3['count'])])

distText = 'Scatter showing min distance from any specialized school using color gradient, and number of specialized test \
takers as marker size. The large, dark circles indicate a school with a large number of students interested in attending \
one of the specialized schools, but that are situated inconveniently far away.'
Ejemplo n.º 5
0
        "primary": "dimgrey",
        "background": "black",
        "font": {
            "color": 'white',
            'size': 17
        },
    },
)

#Resende Bubble Map
resende_bubble = px.scatter_mapbox(
    df_resende_bairro,
    lat='lat',
    lon='long',
    hover_data=['Número de casos', 'Número de mortes'],
    hover_name='Bairro',
    zoom=12.2,
    size='Número de casos',
    height=559 + 25,
    size_max=30,
    center=dict(lat=-22.470, lon=-44.46))

resende_bubble.update_layout(
    mapbox_style='dark',
    mapbox_accesstoken=
    'pk.eyJ1IjoibWF0aGV1c2dhbGhhbm8iLCJhIjoiY2s5YWozZmZyMjQyazNkcGdqZXlzajFraSJ9.mQwhayrKhADgig-Y1MKwSA',
    margin={
        "r": 0,
        "t": 0,
        "l": 0,
        "b": 0
#Train model
count = CountVectorizer()
countVec = count.fit(postmatesBOW['BagOfWords'].values.astype('U'))
count_matrix = countVec.transform(
    postmatesBOW['BagOfWords'].values.astype('U'))

#Plot map figure
fig = px.scatter_mapbox(
    postmates_grouped,
    lat="Latitude",
    lon="Longitude",
    size="scale",
    hover_name="Name",
    hover_data={
        "scale": False,
        "Favorites": True,
        "Latitude": False,
        "Longitude": False
    },
    color="Category",
    zoom=10,
    height=800,
    template="plotly_dark",
)
fig.update_layout(mapbox_style="dark", mapbox_accesstoken=token)
fig.update_traces(marker={'sizemin': 4})
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.update_layout(uirevision=True)

# ------------------------------------------------------------------------------
# App layout
Ejemplo n.º 7
0
def update_output(n_clicks, location, start_date, start_time, end_date,
                  end_time):
    if n_clicks is None:
        raise PreventUpdate
    else:
        # change format of user input info
        start_date = start_date.encode('utf-8')
        end_date = end_date.encode('utf-8')
        start_time = str(start_time)
        end_time = str(end_time)
        lat_long_str = get_coordinates(location)
        dist = str(dist)
        # combine the query for parking
        query_from_user = """SELECT * FROM parking_hourly WHERE ST_DWithin(geoloc, ST_GeomFromText('"""\
            + "Point(" \
            + query_from_user1 + lat_long_str + ")'"\
            + start_date + "' AS date) AND CAST('"\
            + end_date + "' AS date) "\
            + "AND parking_hourly.time BETWEEN CAST('"\
            + start_time + "' AS int) AND CAST('"\
            + end_time + "' AS int) ORDER BY id, date, time ASC;"
        # combine the query for collisions
        col_info = "SELECT * FROM collisions WHERE ST_DWithin(geoloc, ST_GeomFromText" + """(' """\
         + "Point("  + lat_long_str + ")', 4326), 500) AND collisions.date BETWEEN CAST('"\
         + start_date + "' AS date) AND CAST('" + end_date + "' AS date)" \
         + "ORDER BY date, time ASC"

        conn = psycopg2.connect(host = host, \
                port=port, \
                user = user, \
                dbname = db_name, \
                password = password, \
                sslmode='require')

        parking = pd.read_sql_query(query_from_user, conn)
        parking['dot_size'] = parking['total_space'] * 50
        collisions = pd.read_sql_query(col_info, conn)

        # show error information if nothing returned from the query
        if len(parking) == 0:
            fig = px.scatter_mapbox(parking, lat="lat", lon="long",color_discrete_sequence=["#1e2c63"], \
                size= "dot_size", zoom=15, height=600, hover_name="id", hover_data=["total_space"])
            fig.update_layout(mapbox_style="open-street-map")
            fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

            fig.add_trace(
                go.Scattermapbox(
                    mode= "markers+text", \
                    lat=collisions['lat'],\
                    lon=collisions['long'],\
                    marker=go.scattermapbox.Marker(size=20),\
                    text = ['Hit Parked Cars: {}'.format(collisions['hit_parked_car'][i]) for i in range(len(collisions))],\
                    hoverinfo = 'text'
                )
            )

            return '', 'You\'ve entered value that no information found from the database!', dash.no_update, dash.no_update
            raise PreventUpdate

        # update the map per submit
        fig = px.scatter_mapbox(parking, \
            lat="lat", \
            lon="long",\
            color_discrete_sequence=["#1e2c63"],\
            size= "dot_size",
            zoom=15, \
            height=600, \
            hover_name="id", \
            hover_data=["total_space"]
        )

        fig.update_layout(mapbox_style="open-street-map")
        fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

        fig.add_trace(
            go.Scattermapbox(
                mode= "markers+text", \
                lat=collisions['lat'],\
                lon=collisions['long'],\
                marker=go.scattermapbox.Marker(size=20),\
                text = ['Hit Parked Cars: {}'.format(collisions['hit_parked_car'][i]) for i in range(len(collisions))], \
                hoverinfo = 'text'
            )
        )
        fig.update_layout(showlegend=False)

        park_id = parking['id'].unique()

    return 'Here is the result:', '', fig, {
        'data': [
            dict(x=parking[parking['id'] == park_id[i]]["date"],
                 y=parking[parking['id'] == park_id[i]]["occupanc_rate"],
                 mode='plot',
                 text=parking[parking['id'] == park_id[i]]['id'],
                 name=park_id[i]) for i in range(len(park_id))
        ],
        'layout':
        dict(xaxis={'title': 'Date'},
             yaxis={'title': 'Parking Occupancy Rate'},
             legend={i: park_id[i]},
             hovermode='closest',
             plot_bgcolor=colors['background'],
             paper_bgcolor=colors['background'],
             font={'color': colors['sub_title']})
    }
Ejemplo n.º 8
0
def update_map_ui(tab, month, day, region, country, provstate, city,
                  attacktype, year, chart_dp_value, search_value,
                  subtabs2_value):
    df1 = df
    print('worldmap')
    figure = None
    if tab == 'tab-1':
        year_range = range(year[0], year[1] + 1)
        df1 = df1[df1['iyear'].isin(year_range)]
        if (month is None or month == []):
            pass
        else:
            df1 = df1[df1['imonth'].isin(month)]
            if (day is None or day == []):
                pass
            else:
                df1 = df1[df1['iday'].isin(day)]

        if (region is None or region == []):
            pass
        else:
            df1 = df[df['region_txt'].isin(region)]
            if (country is None or country == []):
                pass
            else:
                df1 = df1[df1['country_txt'].isin(country)]
                if (provstate is None or provstate == []):
                    pass
                else:
                    df1 = df1[df1['provstate'].isin(provstate)]
                    if (city is None or city == []):
                        pass
                    else:
                        df1 = df1[df1['city'].isin(city)]

        if (attacktype is None or attacktype == []):
            pass
        else:
            df1 = df1[df1['attacktype1_txt'].isin(attacktype)]
        if (df1.shape[0]):
            pass
        else:
            df1 = pd.DataFrame(columns=[
                'iyear', 'imonth', 'iday', 'region_txt', 'country_txt',
                'provstate', 'city', 'latitude', 'longitude', 'nkill',
                'attacktype1_txt'
            ])
            df1.loc[0] = [
                0, 0, 0, None, None, None, None, None, None, None, None
            ]

        figure = go.Figure()
        figure = px.scatter_mapbox(df1,
                                   lat='latitude',
                                   lon='longitude',
                                   color='attacktype1_txt',
                                   hover_data=[
                                       'region_txt', 'country_txt',
                                       'provstate', 'city', 'attacktype1_txt',
                                       'nkill', 'iyear'
                                   ],
                                   zoom=1,
                                   title='World Map Plot')
        figure.update_layout(mapbox_style='open-street-map',
                             autosize=True,
                             margin=dict(l=0, r=0, t=25, b=20))
    elif tab == 'Chart':
        print(subtabs2_value)
        chart_df = df
        if subtabs2_value == "tab-1":
            if chart_dp_value is not None:
                if search_value is not None:
                    chart_df = df.groupby(
                        "iyear")[chart_dp_value].value_counts().reset_index(
                            name="count")
                    chart_df = chart_df[chart_df[chart_dp_value].str.contains(
                        search_value, case=False)]
                else:
                    chart_df = df.groupby(
                        "iyear")[chart_dp_value].value_counts().reset_index(
                            name="count")

            else:
                raise PreventUpdate

        elif subtabs2_value == 'tab-2':
            if chart_dp_value is not None:
                chart_df = chart_df[chart_df['region_txt'] == 'South Asia']
                chart_df = chart_df[chart_df['country_txt'] == 'India']
                chart_df = chart_df.groupby(
                    "iyear")[chart_dp_value].value_counts().reset_index(
                        name="count")
                if search_value is not None:
                    chart_df = chart_df[chart_df[chart_dp_value].str.contains(
                        search_value, case=False)]
            else:
                raise PreventUpdate

        title = 'Area Chart-Incidents Per Year Grouped By:'
        inci = ''
        for item in chart_dropdown_values:
            if (item.get('value') == chart_dp_value):
                inci = item.get('label')
        title = title + inci

        chartFigure = px.area(chart_df,
                              x="iyear",
                              y="count",
                              color=chart_dp_value,
                              title=title)
        figure = chartFigure

    else:
        return None
    return figure
colors = cm.rainbow(np.linspace(0, 1, 10))
plt.scatter(df.Latitude, df.Longitude, color=colors[df.cluster])

plt.scatter(centroids[:, 0],
            centroids[:, 1],
            color='purple',
            marker='*',
            label='centroid')
plt.xlabel('latitude')
plt.ylabel('longitude')
plt.legend()

fig = px.scatter_mapbox(df,
                        lat="Latitude",
                        lon="Longitude",
                        zoom=10,
                        color="cluster",
                        color_continuous_scale=px.colors.qualitative.G10,
                        height=500,
                        opacity=0.05)
fig.add_trace(
    go.Scattermapbox(lat=centroids[:, 0],
                     lon=centroids[:, 1],
                     mode='markers',
                     marker=go.scattermapbox.Marker(
                         size=10,
                         color='rgb(255, 0, 0)',
                     )))
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()
Ejemplo n.º 10
0
def update_app_ui(Tabs,month_value,date_value,region_value,country_value,state_value,city_value,attack_value,year_value,
                  chart_year_selector, chart_dp_value, search,chartsubtabs):
    fig = None
    if Tabs == "tab1":
        print('Data Type of month value:',str(type(month_value)))
        print('Data Type of date value:',str(type(date_value)))
        print('Data Type of region value:',str(type(region_value)))
        print('Data Type of country value:',str(type(country_value)))
        print('Data Type of state value:',str(type(state_value)))
        print('Data Type of city value:',str(type(city_value)))
        print('Data Type of Attack value:',str(type(attack_value)))    
        print('Data Type of year value:',str(type(year_value)))
        
        # year filter
        year_range = range(year_value[0], year_value[1]+1)
        df1 = df[df["iyear"].isin(year_range)]
        
        # month filter
        if month_value==[] or month_value is None:
            pass
        else:
            if date_value==[] or date_value is None:
                df1 = df1[df1["imonth"].isin(month_value)]
            else:
                df1 = df1[df1["imonth"].isin(month_value)
                                & (df1["iday"].isin(date_value))]
        # region, country, state, city filter
        if region_value==[] or region_value is None:
            pass
        else:
            if country_value==[] or country_value is None :
                df1 = df1[df1["region_txt"].isin(region_value)]
            else:
                if state_value == [] or state_value is None:
                    df1 = df1[(df1["region_txt"].isin(region_value))&
                             (df1["country_txt"].isin(country_value))]
                else:
                    if city_value == [] or city_value is None:
                        df1 = df1[(df1["region_txt"].isin(region_value))&
                        (df1["country_txt"].isin(country_value)) &
                        (df1["provstate"].isin(state_value))]
                    else:
                        df1 = df1[(df1["region_txt"].isin(region_value))&
                        (df1["country_txt"].isin(country_value)) &
                        (df1["provstate"].isin(state_value))&
                        (df1["city"].isin(city_value))]
        #attack type filter           
        if attack_value == [] or attack_value is None:
            pass
        else:
            df1 = df1[df1["attacktype1_txt"].isin(attack_value)] 
        
        mapfigure = go.Figure()
        if df1.shape[0]:
            pass
        else: 
            df1 = pd.DataFrame(columns = ['iyear','imonth','iday','country_txt','region_txt','provstate',
                                          'city','latitude','longitude','attacktype1_txt','nkill'])
            df1.loc[0] = [0, 0 ,0, None, None, None, None, None, None, None, None]
            
        
        mapFigure = px.scatter_mapbox(df1,lat="latitude", 
                                      lon="longitude",
                                      color="attacktype1_txt",
                                      hover_name="city", 
                                      hover_data=["region_txt","country_txt","provstate","city","attacktype1_txt","nkill","iyear","imonth","iday"],
                                      zoom=1)                       
        mapFigure.update_layout(mapbox_style="open-street-map",
                                autosize=True,
                                margin=dict(l=0,r=0,t=25,b=20),
                                )
        fig = mapFigure

    elif Tabs=="chart":
        fig = None
        year_range_c = range(chart_year_selector[0], chart_year_selector[1]+1)
        chart_df = df[df["iyear"].isin(year_range_c)]
        
        
        if chartsubtabs == "tab4":
            pass
        elif chartsubtabs == "tab5":
            chart_df = chart_df[(chart_df["region_txt"]=="South Asia") 
            &(chart_df["country_txt"]=="India")]
        if chart_dp_value is not None and chart_df.shape[0]:
            if search is not None:
                chart_df = chart_df.groupby("iyear")[chart_dp_value].value_counts().reset_index(name = "count")
                chart_df  = chart_df[chart_df[chart_dp_value].str.contains(search, case=False)]
            else:
                chart_df = chart_df.groupby("iyear")[chart_dp_value].value_counts().reset_index(name="count")
        
        if chart_df.shape[0]:
            pass
        else: 
            chart_df = pd.DataFrame(columns = ['iyear', 'count', chart_dp_value])
            chart_df.loc[0] = [0, 0,"No data"]
        chartfigure = px.area(chart_df, x="iyear", y ="count", color = chart_dp_value)
        fig = chartfigure
    return dcc.Graph(figure = fig)
Ejemplo n.º 11
0
            'There are **%d** donors along with you in **2020**. ' %
            len(donor['Donor'].unique()) +
            'They are as kind as you. Thanks to your warm-hearted donate, our world is getting better.'
            +
            "A person's power may be limited. But when the power of many kind people is connected together, it is enough to have an impact on the world"
        )
        st.write(
            'Start your journey in **2021** with us **RIGHT NOW** by clicking the following link:'
        )
        st.write('http://url.com')

        fig = px.scatter_mapbox(
            donor,
            lat='Latitude',
            lon='Longitude',
            hover_name="Donor",
            hover_data=['Date planted', 'Family', 'Genus', 'Species'],
            zoom=17,
            color='label',
            title='Here is <b>your</b> tree!')
        fig.update_layout(mapbox_style="open-street-map")
        fig.update_layout(margin={"r": 0, "l": 0, "b": 0})
        fig.update_layout(width=1000, height=600)

        st.write(fig)

    if select_don == "Donor's trees":
        fig = px.scatter_mapbox(
            donor,
            lat='Latitude',
            lon='Longitude',
Ejemplo n.º 12
0
        if fit:
            stdbscan_fit = ST_DBSCAN(eps1,
                                     eps2,
                                     np.round(np.log(len(np_acled_ame))),
                                     metric='haversine')
            stdbscan_fit.fit(np_acled_ame)

            df_acled_ame['cluster_fit_' + str(eps1) + '_' +
                         str(eps2)] = stdbscan_fit.labels

            fig = px.scatter_mapbox(
                df_acled_ame,
                lat="latitude",
                lon="longitude",
                animation_frame='cluster_fit_' + str(eps1) + '_' + str(eps2),
                zoom=4,
                # center=cent,
                #color_continuous_scale=px.colors.cyclical.IceFire,
                hover_data=[
                    'cluster_fit_' + str(eps1) + '_' + str(eps2), 'latitude',
                    'longitude', 'event_date', 'country', 'actor1', 'actor2'
                ])
            fig.update_layout(mapbox_style="open-street-map")
            fig.write_html('maps/fig_' + str(eps1) + '_' + str(eps2) + '.html')
            end = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(
                end,
                'Finish ST-DBSCAN ',
                'eps1:',
                eps1,
                'eps2',
                eps2,
Ejemplo n.º 13
0
               title='Common Road Features for Accidents in Houston',
               orientation='h')
fig14.update_traces(textposition='outside')
fig14.update_layout(uniformtext_minsize=8,
                    uniformtext_mode='hide',
                    title_x=0.5,
                    height=500)

# GRAPH 15
# ACCIDENT - PRONE SPOTS IN TOP BUSY STREETS IN US
token = 'pk.eyJ1IjoiYmlsaDEiLCJhIjoiY2tpazR5MzM0MDZpYTJ0cW00YmM5MGFicyJ9.x-qdyysjpp-CGnICYerTkw'
# px.set_mapbox_access_token(token)
fig15 = px.scatter_mapbox(mapbox,
                          lat="lat",
                          lon="long",
                          color="Street",
                          color_continuous_scale=px.colors.cyclical,
                          zoom=3,
                          height=600,
                          hover_data=['City', 'Street', 'lat', 'long'])
fig15.update_layout(mapbox_style="dark", mapbox_accesstoken=token)
fig15.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

app.layout = html.Div([
    navbar,
    dbc.Container([
        dbc.Row([dbc.Col(html.H1("USA Accidents Analysis"),
                         className="mb-2")]),
        dbc.Row([
            dbc.Col(html.H6(
                children='Visualising accident trends across the United States'
            ),
Ejemplo n.º 14
0
# # pprint(df5)

df_append_1 = df.append(df1)
# pprint(df_append_1)
df_append_2 = df_append_1.append(df2)
# pprint(df_append_2)
df_append_3 = df_append_2.append(df3)
# pprint(df_append_3)
df_append_4 = df_append_3.append(df4)
# pprint(df_append_4)
df_append_5 = df_append_4.append(df5)
pprint(df_append_5)

fig = px.scatter_mapbox(df_append_5, lat="lat", lon="lng", color="rating", size="user_ratings_total", color_continuous_scale=px.colors.cyclical.IceFire, size_max=30, zoom=15, hover_data=[
    "name",
    "price_level",
    "vicinity"

])

fig.show()





# # df_append_5.to_csv("data2.csv") 




Ejemplo n.º 15
0
def map_each_hospital(features_train,
                      target_train=None,
                      quantile=1.0,
                      quantile_direction='bottom',
                      labels={},
                      midpoint=None,
                      save_file=None,
                      make_plot=True):
    '''
    Map out the locations of hospitals, with marker sizes and colors 
    reflecting the size of the target variable. Map is interactive.


    Parameters
    ----------
    features_train: pandas DataFrame of all features (training data only)
    
    target_train: pandas Series of target values (training data only)

    quantile: float in range [0.0, 1.0]. Indicates what top % of 
        the target data you want displayed (locations outside of
        the defined quantile will not be plotted). A value of 1.0
        (the default) results in all data being plotted. Values less than 0.5 
        are assumed to mean "show me the top X%", whereas values greater 
        than 0.5 are assumed to mean "show me the bottom (1-X)%". Ignored if 
        target_column is None. Use 1.0 if you want to see all data.

    quantile_direction: str. Either 'top' or 'bottom'. Indicates if user 
        wants to see the "top X%" quantile or the "bottom X%" 
        quantile. Use 'bottom' if you want to see all data.

    labels: dict with str keys and str values. By default, column names are 
        used in the figure for axis titles, legend entries and hovers. This 
        parameter allows this to be overridden. The keys of this dict should 
        correspond to column names, and the values should correspond to the 
        desired label to be displayed (e.g. {target_column: 'Heart Attacks'})

    midpoint: float. If set, indicates the value of target_train that you
        want as the midpoint of the color scale used

    save_file: str. Should provide a filepath for the interactive HTML 
        to be saved. If None, file is not saved.

    make_plot: bool. If True, automatically plots the resultant figure


    Returns
    -------
    Plots an interactive (plotly-driven) map of all locations with
    marker sizes and color corresponding to the target variable values. Also returns a plotly go.Figure object

    '''

    # Pass in my public mapbox token for contextual mapping
    px.set_mapbox_access_token(open("secure_keys/public.mapbox_token").read())

    data = features_train.copy()

    # Setup figure title
    if quantile == 1.0:
        title = "All Data"
    elif quantile_direction == 'top':
        title = f"Top {int(quantile * 100)}%"
    else:
        title = f"Bottom {int(quantile * 100)}%"

    # Combine features and target, if target is specified
    if target_train is not None:
        target_column = target_train.name

        # Combine target and features
        data[target_column] = target_train

        # 'top' -> at or above
        if quantile_direction == 'top':
            print(f"Only showing values at or above \
            {data.quantile(1-quantile)[target_column]}")

            top_target_quantile = data[data[target_column] >= \
            data.quantile(1-quantile)[target_column]]

        # Assume when a large quantile is given, users wants "this % and lower"
        elif quantile_direction == 'bottom':
            print(f"Only showing values at or below \
            {data.quantile(quantile)[target_column]}")

            top_target_quantile = data[data[target_column]\
             <= data.quantile(quantile)[target_column]]

        else:
            raise ValueError(
                "Invalid value for quantile_direction. Use 'top' or 'bottom'.")

        # Map only top X% of target value with color scale midpoint at median of whole dataset
        if midpoint is None: midpoint = target_train.quantile(0.5)

        fig = px.scatter_mapbox(
            top_target_quantile,
            lat="Latitude",
            lon="Longitude",
            color=target_column,
            size=target_column,
            size_max=7,
            zoom=2,
            opacity=0.25,
            color_continuous_scale=px.colors.diverging.Portland,
            color_continuous_midpoint=midpoint,
            labels=labels,
            title=title)

    # No target data provided
    else:
        fig = px.scatter_mapbox(data,
                                lat="Latitude",
                                lon="Longitude",
                                zoom=2,
                                labels=labels,
                                title=title,
                                opacity=0.25)

    if save_file:
        fig.write_html(save_file)

    if make_plot: fig.show()

    return fig
Ejemplo n.º 16
0
st.markdown("----------")
####Visualization 4######
expander3 = st.beta_expander("Click for More Information", expanded=False)

px.set_mapbox_access_token(
    "pk.eyJ1IjoiZ2VlbWFuMTIwOSIsImEiOiJja291aTI5bjAwbDZ6Mm9sbGVxb292c3NiIn0.eKZKp_JepI5fBsYRa2cdzw"
)

fig5 = px.scatter_mapbox(dfinal,
                         lat="latitude",
                         lon="longitude",
                         animation_frame="DATA_YEAR",
                         animation_group="BIAS_DESC",
                         color="BIAS_DESC",
                         hover_name="BIAS_DESC",
                         size="VICTIM_COUNT",
                         hover_data=["target_loc"],
                         color_continuous_scale=px.colors.cyclical.IceFire,
                         size_max=35,
                         zoom=3,
                         width=1500)

fig5.update_layout(
    title=
    'Hate Crimes per year<br>(Hover for City,State/Bias Description/Victim Count)',
    autosize=True,
    geo_scope='usa',
)
st.plotly_chart(fig5)
Ejemplo n.º 17
0
    r="frequency",
    theta="direction",
    color="strength",
    template="plotly_dark",
    color_discrete_sequence=px.colors.sequential.Plasma[-2::-1],
)
fig.write_html(os.path.join(dir_name, "bar_polar.html"))

# #### Maps

carshare = px.data.carshare()
fig = px.scatter_mapbox(
    carshare,
    lat="centroid_lat",
    lon="centroid_lon",
    color="peak_hour",
    size="car_hours",
    color_continuous_scale=px.colors.cyclical.IceFire,
    size_max=15,
    zoom=10,
)
fig.write_html(os.path.join(dir_name, "scatter_mapbox.html"))

carshare = px.data.carshare()
fig = px.line_mapbox(carshare,
                     lat="centroid_lat",
                     lon="centroid_lon",
                     color="peak_hour")
fig.write_html(os.path.join(dir_name, "line_mapbox.html"))

sample_geojson = {
    "type":
Ejemplo n.º 18
0
        h1_pos_diario / h1_tot_diario, h2_pos_diario / h2_tot_diario,
        super1_pos_diario / super1_tot_diario,
        super2_pos_diario / super2_tot_diario, t1_pos_diario / t1_tot_diario,
        t2_pos_diario / t2_tot_diario, t3_pos_diario / t3_tot_diario,
        t4_pos_diario / t4_tot_diario, uni_pos_diario / uni_tot_diario
    ]
})

#BubbleMap DIARIO:
mapa = px.scatter_mapbox(city_diario,
                         lat="latitude",
                         lon="longitude",
                         hover_name="edificio",
                         hover_data=["edificio", "ia"],
                         color="pcr_positivo",
                         size_max=25,
                         zoom=12,
                         height=600,
                         size=city_diario["pcr_positivo"],
                         color_continuous_scale=[(0.00, "green"),
                                                 (0.5, "green"), (0.5, "red"),
                                                 (1.00, "red")],
                         labels={"pcr_psitivo": "Casos positivos"})

mapa.update_layout(mapbox_style="open-street-map", height=450)
mapa.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}, autosize=True)

# Datos ACUMULADOS

# Eliminamos duplicados id ACUMULADO
cc = cc[cc.pcr == 'Positivo'].drop_duplicates(subset='id', keep="first")
c1 = c1[c1.pcr == 'Positivo'].drop_duplicates(subset='id', keep="first")
Ejemplo n.º 19
0
parking['dot_size'] = parking['total_space'] * 50
park_id = parking['id'].unique()
print(park_id)

collisions = pd.read_sql_query(col_info, conn)
collisions['dot_size'] = collisions['veh_count'] * 120

available_indicators = [
    6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
]

print(collisions.head(3))
print(len(collisions))

# add parking map to the website
fig = px.scatter_mapbox(parking, lat="lat", lon="long",color_discrete_sequence=["#1e2c63"], \
    size= "dot_size", zoom=15, height=450)
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

# add collision info
fig.add_trace(
    go.Scattermapbox(
        mode= "markers+text", \
        lat=collisions['lat'],\
        lon=collisions['long'],\
        marker=go.scattermapbox.Marker(size=20),\
        text = ['Hit Parked Cars: {}'.format(collisions['hit_parked_car'][i]) for i in range(len(collisions))], \
        hoverinfo = 'text'
    )
)
Ejemplo n.º 20
0
def update_figures(option):
    today = datetime.datetime.now(tz=tz.gettz('Europe/Helsinki'))
    date_ = today.date().isoformat()
    hour_ = today.time().hour
    minute_ = today.time().minute

    update_time_fi = f"Aineisto on peräisin Helsingin Sanomien avoimesta rajapinnasta." \
                  f" Päivitetty {date_} klo {hour_}.{minute_:02}."
    update_time_en = f"Data from API by Helsingin Sanomat." \
                  f" Updated {date_} {hour_:02}:{minute_:02}."

    if option == 'total':
        size_col = 'active'

        data, all_data = get_data(
            START_DATE,
            END_DATE,
            cumulative=True,
        )

    elif option == 'deaths':
        size_col = 'deaths'

        data, all_data = get_data(
            '2020-03-20',
            END_DATE,
            cumulative=True,
        )

    else:
        size_col = 'confirmed'

        data, all_data = get_data(
            START_DATE,
            END_DATE,
            cumulative=False,
        )

    fig1 = px.scatter_mapbox(
        data,
        lat='lat',
        lon='lon',
        color='shp',
        hover_name='shp',
        hover_data='confirmed deaths recovered'.split(),
        size=size_col,
        animation_frame='pvm',
        center={
            'lat': 63.4,
            'lon': 26.0
        },
        zoom=4,
        size_max=36,
        height=600,
        width=None,
        opacity=OPACITY,
    )
    fig1.update_layout(mapbox_style="carto-darkmatter")

    fig2 = px.bar(
        data,
        x='pvm',
        y=size_col,
        color='shp',
        hover_name='shp',
        height=520,
        width=None,
        opacity=OPACITY,
    )

    fig3 = px.line(
        all_data,
        x='pvm',
        y=size_col,
        height=520,
        width=None,
    )

    if option == 'confirmed':
        fig3_title = 'Koko maa | All Finland'
    else:
        fig3.update_layout(yaxis_type='log')
        fig3_title = 'Koko maa, logaritminen asteikko | All Finland, logarithmic scale'

    return fig1, fig2, fig3, fig3_title, update_time_fi, update_time_en
Ejemplo n.º 21
0
                     colors='red',
                     how='spline',
                     mode='lines',
                     item='Maize',
                     title='Maize Production in Somalia from 2014 - 2018')

fig3 = px.scatter_mapbox(dd.total_element('production', 'Maize'),
                         lat='Lat',
                         lon='Lon',
                         color='Total',
                         hover_name='Area',
                         size='Total',
                         hover_data={
                             'Lat': False,
                             'Lon': False
                         },
                         labels={'Area': 'Element'},
                         color_continuous_scale=colors,
                         zoom=1.4,
                         width=1900,
                         height=700,
                         template='presentation',
                         center=None,
                         mapbox_style='light',
                         title='Global Maize Production in Tonnes(2014-2018)')

fig4 = data[data['Element'] == 'Production'].iplot(
    asFigure=True,
    kind='pie',
    labels='Area',
    values='Y2018',
Ejemplo n.º 22
0
def plotly_relieve(year, hazard):
    df = wildfires_data()
    clustering = wildfires_clustering()

    # I put in a new dataframe the species and the labels so I can figure out which label has each specie
    df['labels'] = clustering['labels']

    values = labels_based_effect(df, df['SIZE_HA'])
    df['colors'] = df['labels'].apply(lambda x: labeling(x, values))

    df = df[(df['YEAR'] == year)]  # I get the year I want

    latitude = df['LATITUDE']
    longitude = df['LONGITUDE']
    text = "date:" + df['YEAR'].astype(str) + "-" + df['MONTH'].astype(
        str) + " - HA affected:" + df['SIZE_HA'].astype(
            str) + " - Province: " + df['SRC_AGENCY'].astype(str)

    if hazard == "Tornadoes":
        df = tornadoes_data()
        clustering = tornadoes_clustering()

        df['labels'] = clustering['labels']
        df['effect'] = df['FUJITA'].astype(int) + df['HUMAN_FATAL'].astype(
            int) + df['HUMAN_INJ']
        values = labels_based_effect(df, df['effect'])
        df['colors'] = df['labels'].apply(lambda x: labeling(x, values))

        df = df[(df['YYYY_LOCAL'] == year)]  # I get the year I want

        latitude = df['START_LAT_N']
        longitude = df['START_LON_W']
        text = "date" + df['YYYY_LOCAL'].astype(
            str) + " - " + df['MM_LOCAL'].astype(
                str) + " - Place: " + df['NEAR_CMMTY'].astype(str)
    if hazard == "Earthquakes":
        df = earthquakes_data()
        clustering = earthquakes_clustering()

        df['labels'] = clustering['labels']
        values = labels_based_effect(df, df['depth'])
        df['colors'] = df['labels'].apply(lambda x: labeling(x, values))

        df = df[(df['YEAR'] == year)]  # I get the year I want

        latitude = df['latitude']
        longitude = df['longitude']
        text = "date:" + df['date'] + "- depth:" + df['depth'].astype(
            str) + "- magnitude:" + df['magnitude'].astype(
                str) + "- place:" + df['place'].astype(str)
    if hazard == "Floods":
        df = floods_data()
        clustering = floods_clustering()

        df['labels'] = clustering['labels']
        df['effect'] = df['FATALITIES'] + df['INJURED / INFECTED'] + df[
            'EVACUATED']
        values = labels_based_effect(df, df['effect'])
        df['colors'] = df['labels'].apply(lambda x: labeling(x, values))

        df = df[(df['YEAR'] == year)]  # I get the year I want

        latitude = df['LATITUDE']
        longitude = df['LONGITUDE']
        text = "date: " + df['EVENT'].astype(
            str) + "- injured & fatalities & evacuated:" + df['effect'].astype(
                str) + " - place:" + df['PLACE'].astype(str)
    if hazard == "Hurricanes":
        df = hurricanes_data()
        clustering = hurricanes_clustering()

        df['labels'] = clustering['labels']
        df['effect'] = df['FATALITIES'] + df['INJURED / INFECTED'] + df[
            'EVACUATED']
        values = labels_based_effect(df, df['effect'])
        df['colors'] = df['labels'].apply(lambda x: labeling(x, values))

        df = df[(df['YEAR'] == year)]  # I get the year I want

        latitude = df['LATITUDE']
        longitude = df['LONGITUDE']
        text = "date: " + df['EVENT'].astype(
            str) + "- injured & fatalities & evacuated:" + df['effect'].astype(
                str) + " - place:" + df['PLACE'].astype(str)

    fig = px.scatter_mapbox(df,
                            lat=latitude,
                            lon=longitude,
                            hover_name=text,
                            color='colors',
                            zoom=3)
    fig.update_layout(
        mapbox_style="white-bg",
        mapbox_layers=[{
            "below":
            'traces',
            "sourcetype":
            "raster",
            "sourceattribution":
            "United States Geological Survey",
            "source": [
                "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"
            ]
        }, {
            "sourcetype":
            "raster",
            "sourceattribution":
            "Government of Canada",
            "source": [
                "https://geo.weather.gc.ca/geomet/?"
                "SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&BBOX={bbox-epsg-3857}&CRS=EPSG:3857"
                "&WIDTH=1000&HEIGHT=1000&LAYERS=RADAR_1KM_RDBR&TILED=true&FORMAT=image/png"
            ],
        }])
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    return fig
Ejemplo n.º 23
0
        # "vicinity4": data_0["results"][3]["vicinity"],
        # "vicinity5": data_0["results"][4]["vicinity"]
    }


restaurant_list = []

data_0 = extract_data_0(
    requests.get(url2,
                 params={
                     "location": lat_lng,
                     "radius": 1000,
                     "type": "restaurant",
                     "key": api_key
                 }).json())

restaurant_list.append(data_0)
# pprint(restaurant_list)

# df = pd.DataFrame(restaurant_list).drop_duplicates()
# pprint(df)

df = pd.DataFrame(restaurant_list)
pprint(df)

fig = px.scatter_mapbox(df, lat="lat", lon="lng")

fig.show()

# # df_append_4.to_csv("data2.csv")
Ejemplo n.º 24
0
def plotly_states(year, hazard):
    df = wildfires_data()
    clustering = wildfires_clustering()

    # I put in a new dataframe the species and the labels so I can figure out which label has each specie
    df['labels'] = clustering['labels']

    values = labels_based_effect(df, df['SIZE_HA'])

    df['colors'] = df['labels'].apply(lambda x: labeling(x, values))
    df = df[(df['YEAR'] == year)]  # I get the year I want

    latitude = df['LATITUDE']
    longitude = df['LONGITUDE']
    text = "date:" + df['YEAR'].astype(str) + "-" + df['MONTH'].astype(
        str) + " - HA affected:" + df['SIZE_HA'].astype(
            str) + " - Province: " + df['SRC_AGENCY'].astype(str)

    if hazard == "Tornadoes":
        df = tornadoes_data()
        clustering = tornadoes_clustering()

        df['labels'] = clustering['labels']
        df['effect'] = df['FUJITA'].astype(int) + df['HUMAN_FATAL'].astype(
            int) + df['HUMAN_INJ']
        values = labels_based_effect(df, df['effect'])
        df['colors'] = df['labels'].apply(lambda x: labeling(x, values))
        df = df[(df['YYYY_LOCAL'] == year)]  # I get the year I want

        latitude = df['START_LAT_N']
        longitude = df['START_LON_W']
        text = "date" + df['YYYY_LOCAL'].astype(
            str) + " - " + df['MM_LOCAL'].astype(
                str) + " - Place: " + df['NEAR_CMMTY'].astype(str)
    if hazard == "Earthquakes":
        df = earthquakes_data()
        clustering = earthquakes_clustering()

        df['labels'] = clustering['labels']
        values = labels_based_effect(df, df['depth'])
        df['colors'] = df['labels'].apply(lambda x: labeling(x, values))
        df = df[(df['YEAR'] == year)]  # I get the year I want

        latitude = df['latitude']
        longitude = df['longitude']
        text = "date:" + df['date'] + "- depth:" + df['depth'].astype(
            str) + "- magnitude:" + df['magnitude'].astype(
                str) + "- place:" + df['place'].astype(str)
    if hazard == "Floods":
        df = floods_data()
        clustering = floods_clustering()

        df['labels'] = clustering['labels']
        df['effect'] = df['FATALITIES'] + df['INJURED / INFECTED'] + df[
            'EVACUATED']
        values = labels_based_effect(df, df['effect'])
        df['colors'] = df['labels'].apply(lambda x: labeling(x, values))
        df = df[(df['YEAR'] == year)]  # I get the year I want

        latitude = df['LATITUDE']
        longitude = df['LONGITUDE']
        text = "date: " + df['EVENT'].astype(
            str) + " - injured & fatalities & evacuated:" + df[
                'effect'].astype(str) + " - place:" + df['PLACE'].astype(str)
    if hazard == "Hurricanes":
        df = hurricanes_data()
        clustering = hurricanes_clustering()

        df['labels'] = clustering['labels']
        df['effect'] = df['FATALITIES'] + df['INJURED / INFECTED'] + df[
            'EVACUATED']
        values = labels_based_effect(df, df['effect'])
        df['colors'] = df['labels'].apply(lambda x: labeling(x, values))

        df = df[(df['YEAR'] == year)]  # I get the year I want

        latitude = df['LATITUDE']
        longitude = df['LONGITUDE']
        text = "date: " + df['EVENT'].astype(
            str) + "- injured & fatalities & evacuated:" + df['effect'].astype(
                str) + " - place:" + df['PLACE'].astype(str)

    fig = px.scatter_mapbox(df,
                            lat=latitude,
                            lon=longitude,
                            hover_name=text,
                            color='colors',
                            zoom=3)
    fig.update_layout(mapbox_style="open-street-map")
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    return fig
Ejemplo n.º 25
0
def update_app_ui(month_value, day_value, region_value, country_value,
                  state_value, city_value, attack_value, year_value):

    global dfnew
    dfnew = df  # dfnew so that if we unselect option, it must show the previous result

    if (year_value != None):
        global df1
        n = [x for x in range(year_value[0], year_value[1] + 1)]
        df1 = pd.DataFrame()
        print(n)
        for i in n:
            df2 = pd.DataFrame(df[df['iyear'] == i])
            df1 = df1.append(df2)
        dfnew = df1

    if (month_value != None):
        dfnew = df1  #before changing df1 value, i need to store the values in dfnew so if we unselect we get the previous values
        df1 = pd.DataFrame(df[df['imonth'].isin(month_value)])

        if (day_value != None):
            dfnew = df1
            dfd = pd.DataFrame(df[df['iday'].isin(day_value)])
            df1 = df1.merge(dfd)
            print('df1 is', df1)

    if (region_value != None):
        dfnew = df1
        df3 = pd.DataFrame(df[df['region_txt'].isin(region_value)])
        df1 = df1.merge(df3)
        print(df1)

        if (country_value != None):
            dfnew = df1
            dfc = pd.DataFrame(df[df['country_txt'].isin(country_value)])
            df1 = df1.merge(dfc)

        if (state_value != None):
            dfnew = df1
            dfs = pd.DataFrame(df[df['provstate'].isin(state_value)])
            df1 = df1.merge(dfs)

        if (city_value != None):
            dfnew = df1
            dfy = pd.DataFrame(df[df['city'].isin(city_value)])
            df1 = df1.merge(dfy)

        if (attack_value != None):
            dfnew = df1
            dfa = pd.DataFrame(df[df['attacktype1_txt'].isin(attack_value)])
            df1 = df1.merge(dfa)

    if (attack_value != None):
        dfnew = df1
        dfa = pd.DataFrame(df[df['attacktype1_txt'].isin(attack_value)])
        df1 = df1.merge(dfa)

    if df1.empty:
        value = 'Results Found'
        fig = px.scatter_mapbox(dfnew,
                                lat=dfnew["latitude"],
                                lon=dfnew["longitude"],
                                hover_name=dfnew["city"],
                                hover_data=[
                                    'region_txt', 'country_txt', 'provstate',
                                    'city', 'attacktype1_txt', 'nkill',
                                    'imonth', 'iday'
                                ],
                                color='attacktype1_txt',
                                zoom=2,
                                height=500)
        fig.update_layout(mapbox_style="open-street-map")
        fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    else:
        value = 'Results Found'
        print(df1)
        fig = px.scatter_mapbox(df1,
                                lat=df1["latitude"],
                                lon=df1["longitude"],
                                hover_name=df1["city"],
                                hover_data=[
                                    'region_txt', 'country_txt', 'provstate',
                                    'city', 'attacktype1_txt', 'nkill',
                                    'imonth', 'iday'
                                ],
                                color='attacktype1_txt',
                                zoom=2,
                                height=500)
        fig.update_layout(mapbox_style="open-street-map")
        fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

    return fig, value
Ejemplo n.º 26
0
    # We calculate the approximate center of all the points to set the initial position of our map
    c_lat = (df["latitude"].max() + df["latitude"].min()) / 2
    c_lon = (df["longitude"].max() + df["longitude"].min()) / 2

    # Since we have defined 3 posibilities of maps on the dropbox, we will have three different
    # cases we will have to code. These should ideally have been modulated into other files,
    # but we've decised to keep it into a single file to simplify for this workshop.

    # The first map is a simple scatter over the world
    if map_type == "Global distribution":
        # We create a map with the points of our dataframe
        my_map = px.scatter_mapbox(df,
                                   lat="latitude",
                                   lon="longitude",
                                   hover_name="city",
                                   zoom=1,
                                   center={
                                       "lat": c_lat,
                                       "lon": c_lon
                                   })
        # We use open-street-map because it needs no token
        my_map.update_layout(mapbox_style="open-street-map")
        # This sets the padding for the map within it's space
        my_map.update_layout(margin={"r": 10, "t": 0, "l": 0, "b": 0})

    # The second option is a choropleth map, therefore we will need the geojson file with the
    # polygons that draw the borders of the countries
    if map_type == "By country":
        with open('data/countries.geojson', 'r') as data:
            countries = json.load(data)
        # We also group the data by country so we can get a count of entries for each
Ejemplo n.º 27
0
##########################################################################
##########################################################################
kmeans = KMeans(n_clusters=3, init='k-means++')
kmeans.fit(X3[X2.columns[0:3]])  # Compute k-means clustering.
X3['cluster_label'] = kmeans.fit_predict(X3[X2.columns[0:3]])
centers = kmeans.cluster_centers_  # Coordinates of cluster centers.
labels = kmeans.predict(X3[X2.columns[0:3]])  # Labels of each point

##########################################################################
##########################################################################
fig = go.Figure()
fig = px.scatter_mapbox(X3,
                        lat="lat",
                        lon="lon",
                        color="cluster_label",
                        zoom=5,
                        size="Deaths",
                        animation_frame="date",
                        height=750,
                        hover_name="Province/State")
fig.update_layout(mapbox_style="stamen-terrain")
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

########### Initiate the app
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server

# app.layout = html.Div([
#
# ], style={'display' : 'flex', 'flex-direction' : 'column', 'align-items':'center'})
Ejemplo n.º 28
0
ds.iloc[:,0]
ds.loc[:,'id']
cols=[True, False,False, False,False, False,False, False,False, False,False,
      False,False, False,False, False,False, False,False,False, False,False]
ds.loc[:,cols]

#19. Salve um arquivo .csv com somente as colunas do item 10.
idd=ds['id']
idd.to_csv('new.csv',index=False)

import plotly.express as px

data_map=ds[['id','lat','long','price','condition']]
mapa=px.scatter_mapbox(data_map, lat='lat', lon='long', hover_name='id',
               hover_data=['price'],
               color='condition',
               zoom=9,
               size='price',
               height=300)

mapa.update_layout(mapbox_style='open-street-map')
mapa.update_layout(height=600,margin={'r':0,'t':0,'l':0, 'b':0})
mapa.show()

mapa.write_html('mapa_house_rocket.html')






Ejemplo n.º 29
0
def initial_map():
    
    ts_confirmed, ts_death, ts_recovered = get_data_from_postgres()
    
    date = ts_recovered.columns[-2]
    
    zoom = 2    
    
    filtered_ts_confirmed = ts_confirmed
    filtered_ts_death = ts_death
    filtered_ts_recovered = ts_recovered
    
    px.set_mapbox_access_token(mapbox_access_token)
        
    ## Rename columns to prettify hover data
    temp_deaths_df = filtered_ts_death.rename(columns = {date:'Deaths', 'Lat':'Latitude', 'Long':'Longitude'})
    temp_recovered_df = filtered_ts_recovered.rename(columns = {date:'Recovered', 'Lat':'Latitude', 'Long':'Longitude'})
    temp_confirmed_df = filtered_ts_confirmed.rename(columns = {date:'Confirmed', 'Lat':'Latitude', 'Long':'Longitude'})

    #Some data from JHU appears as -1 unsure why
    temp_recovered_df[temp_recovered_df['Recovered'] < 0] = 0
    temp_confirmed_df[temp_confirmed_df['Confirmed'] < 0] = 0
    temp_deaths_df[temp_deaths_df['Deaths'] < 0] = 0

    #assumes order of countries from datasets are the same
    temp_all = temp_confirmed_df[['City/Country', 'Confirmed','Latitude','Longitude']]
    temp_all.insert(2,'Deaths', temp_deaths_df[['Deaths']])
    temp_all.insert(2,'Recovered',temp_recovered_df[['Recovered']])
    
    fig = px.scatter_mapbox(temp_all, lat="Latitude", lon="Longitude", color="Deaths", size="Confirmed",
                          #color_continuous_scale=px.colors.diverging.Picnic,
                          size_max=50, hover_name="City/Country",
                          #hover_data=["Confirmed", "Recovered", "Deaths"], 
                          hover_data=["Confirmed", "Deaths"], 
                          )
    fig.update_traces(hoverinfo='text', marker=dict(sizemin=2),showlegend=False)
    
    fig.update(
            layout=dict(title=dict(x=0.5), paper_bgcolor=colors['background'] )
        )
    
    fig.update_layout(
        autosize=True,
        height=750,
        #width=1500,
        font={
            'family': 'Courier New, monospace',
            'size': 18,
            'color': 'white'
        },
        hovermode='closest',
        legend=dict(
            font={'color':colors['background']},
            ),
        mapbox=dict(
            accesstoken=mapbox_access_token,
            bearing=0,
            style="dark",
            # center=dict(
            #     lat=56,
            #     lon=324
            # ),
            pitch=0,
            zoom=zoom
            ),
    )
       
    return fig
Ejemplo n.º 30
0
import dash_html_components as html
import pandas as pd
import numpy as np

import plotly.express as px
from dash.dependencies import Input, Output

df = pd.read_csv('finals.csv')

app = dash.Dash(__name__)
server = app.server

fig = px.scatter_mapbox(df,
                        lat="latitude",
                        lon="longitude",
                        hover_name="location",
                        hover_data=["Severity Type"],
                        color_discrete_sequence=["red"],
                        zoom=3,
                        height=500)
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

#all_options = {
#    'One Location': [
#        dcc.Input(id='my-id', value='initial value', type='text'),
#        html.Div(id='my-div')],
#    'Many Locations': [
#        dcc.Input(id='my-id', value='initial value', type='text'),
#        html.Div(id='my-div')]
#}