Exemple #1
0
#-----
st.subheader("Map of all pickups")
#st.map(data)
st.pydeck_chart(
    pdk.Deck(layers=[
        pdk.Layer(
            "HeatmapLayer",
            data=data,
            opacity=0.9,
            get_position=["lon", "lat"],
            aggregation=pdk.types.String("MEAN"),
            color_range=[[240, 249, 232], [204, 235, 197], [168, 221, 181],
                         [123, 204, 196], [67, 162, 202], [8, 104, 172]],
            threshold=1,
            pickable=True,
        )
    ],
             initial_view_state=pdk.ViewState(latitude=40.720589,
                                              longitude=-73.856084,
                                              zoom=8,
                                              min_zoom=5,
                                              max_zoom=15,
                                              pitch=40.5,
                                              bearing=-27.36),
             tooltip={"text": "Concetration of pickups"}))

#slider
st.subheader('Map of pickups by hour')
hour_filter = st.slider('Select hour', 0, 23, 17)
#mapa
view = pdk.ViewState(
    longitude=139.691648,
    latitude=35.689185,
    zoom=4,
    pitch=40.5,
)

layer = pdk.Layer("HeatmapLayer",
                  data=df_pref_map,
                  opacity=0.4,
                  get_position=["lon", "lat"],
                  threshold=0.3,
                  get_weight='一人当たり賃金(相対値)')

layer_map = pdk.Deck(
    layers=layer,
    initial_view_state=view,
)

st.pydeck_chart(layer_map)

show_df = st.checkbox('Show DataFrame')
if show_df == True:
    st.write(df_pref_map)

st.header('■集計年別の一人当たり賃金(万円)の推移')

df_ts_mean = df_jp_ind[(df_jp_ind["年齢"] == "年齢計")]
df_ts_mean = df_ts_mean.rename(columns={'一人当たり賃金(万円)': '全国_一人当たり賃金(万円)'})

df_pref_mean = df_pref_ind[(df_pref_ind['年齢'] == '年齢計')]
pref_list = df_pref_mean['都道府県名'].unique()
    radius_max_pixels=100,
    line_width_min_pixels=1,
    get_position="coordinates",
    get_radius="exits_radius",
    get_fill_color=[255, 140, 0],
    get_line_color=[0, 0, 0],
)

# Set the viewport location
view_state = pdk.ViewState(latitude=37.7749295,
                           longitude=-122.4194155,
                           zoom=10,
                           bearing=0,
                           pitch=0)

# Render
r = pdk.Deck(layers=[layer], initial_view_state=view_state)

app = dash.Dash(__name__)

app.layout = html.Div(
    dash_deck.DeckGL(
        r.to_json(),
        id="deck-gl",
        tooltip={"text": "{name}\n{address}"},
        mapboxKey=mapbox_api_token,
    ))

if __name__ == "__main__":
    app.run_server(debug=True)
Exemple #4
0
st.pydeck_chart(
    pdk.Deck(
        map_style='mapbox://styles/mapbox/light-v9',
        initial_view_state=pdk.ViewState(
            latitude=28.7,
            longitude=77.102,
            zoom=3.5,
            pitch=50,
        ),
        layers=[
            pdk.Layer(
                'HexagonLayer',
                data=df,
                get_position='[lon, lat]',
                radius=80000,
                elevation_scale=10,
                elevation_range=[0, 1000],
                pickable=True,
                extruded=True,
            ),
            pdk.Layer(
                'ScatterplotLayer',
                data=df,
                get_position='[lon, lat]',
                get_color='[200, 30, 0, 160]',
                get_radius=80000,
            ),
        ],
    ))

if gem == "Corundum - Blue Sapphire":
Exemple #5
0
midpoint = (np.average(data['latitude']), np.average(data['longitude']))
#Create a 3D map with pydeck
st.write(
    pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",
        initial_view_state={
            "latitude": midpoint[0],
            "longitude": midpoint[1],
            "zoom": 12,
            "pitch": 50,
        },
        layers=[
            pdk.Layer("HexagonLayer",
                      data=data[['Price_m2_USD', 'latitude', 'longitude']],
                      get_position=['longitude', 'latitude'],
                      radius=50,
                      extruded=True,
                      pickable=False,
                      elevation_scale=1,
                      elevation_range=[
                          min(data['Price_m2_USD']),
                          max(data['Price_m2_USD'])
                      ],
                      auto_highlight=True,
                      coverage=1),
        ],
    ))

#Disclaimer
st.write(
    '<html lang="es"><html translate="no">',
Exemple #6
0
df = df[df[["lng_w", "lat_w"]].apply(lambda row: in_bounding_box(row), axis=1)]

GREEN_RGB = [0, 255, 0, 40]
RED_RGB = [240, 100, 0, 40]

arc_layer = pydeck.Layer("ArcLayer",
                         data=df,
                         get_width="S000 * 2",
                         get_source_position=["lng_h", "lat_h"],
                         get_target_position=["lng_w", "lat_w"],
                         get_tilt=15,
                         get_source_color=RED_RGB,
                         get_target_color=GREEN_RGB,
                         pickable=True,
                         auto_highlight=True)

view_state = pydeck.ViewState(
    latitude=37.7576171,
    longitude=-122.5776844,
    bearing=45,
    pitch=50,
    zoom=8,
)

TOOLTIP_TEXT = {
    "html":
    "{S000} jobs <br /> Home of commuter in red; work location in green"
}
r = pydeck.Deck(arc_layer, initial_view_state=view_state, tooltip=TOOLTIP_TEXT)
r.to_html("arc_layer.html", notebook_display=False)
Exemple #7
0
st.markdown("Vehicle collisions between %i:00 and %i:00" % (hour,
                                                            (hour + 1) % 24))

midpoint = (np.average(data["latitude"]), np.average(data["longitude"]))
st.write(
    pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",
        initial_view_state={
            "latitude": midpoint[0],
            "longitude": midpoint[1],
            "zoom": 11,
            "pitch": 50,
        },
        layers=[
            pdk.Layer(
                "HexagonLayer",
                data=data[['date/time', 'latitude', 'longitude']],
                get_position=["longitude", "latitude"],
                auto_highlight=True,
                radius=100,
                extruded=True,
                pickable=True,
                elevation_scale=4,
                elevation_range=[0, 1000],
            ),
        ],
    ))
if st.checkbox("Show raw data", False):
    st.subheader("Raw data by minute between %i:00 and %i:00" %
                 (hour, (hour + 1) % 24))
    st.write(data)
Exemple #8
0
def monta_estados(taxa_mortalidade):
    df = load_data_brasil_io()
    states = df['state'].sort_values(ascending=True).unique()
    if states is not None:
        state = st.sidebar.selectbox('Qual o estado você deseja visualizar?', states)

        dados_estado =df[(df['state'] == state)&(df['place_type']=='state')]
        dados_estado_cities =df[(df['state'] == state)&(df['place_type'] != 'state')]

        st.subheader(f"Dados de COVID em {state}")

        dados_estado_plot = dados_estado[['date', 'confirmed', 'deaths']].sort_values(by=['date'], ascending=True)
        dados_estado_plot.reset_index(drop=True, inplace=True)
        dados_estado_plot.set_index(['date'], inplace=True)

        hoje = dados_estado[dados_estado['is_last']]
        hoje.reset_index(drop=True, inplace=True)
        dia_atual = hoje['date'].dt.strftime('%d-%m-%Y')[0]

        confirmados = hoje['confirmed'][0]
        mortes = hoje['deaths'][0]
        quantidade_estimada = (100 * mortes / taxa_mortalidade).astype(int)
        taxa = round(hoje['death_rate'][0] * 10000) / 100

        st.markdown(f"O estado de **{state}** teve até o dia **{dia_atual}** "
                    f"um total de **{confirmados}** casos confirmados e"
                    f" **{mortes}** mortes com uma taxa de mortalidade de **{taxa}%**.")
        if mortes > 0:
            st.markdown(f"Com base na taxa de mortalidade de outros países (**{taxa_mortalidade}%** dos infectados) "
                        f"a quantidade estimada de infectados seria de **{quantidade_estimada}** para a quantidade de mortos atual.")

        #st.line_chart(dados_estado_plot)

        data_state = get_map_state(state)
        data_cities = get_map_city(state)
        view = get_view(state)

        slide =  st.slider('Semana epidemiológica', 0, 255, 1 )

        dia_atual_mapa = dados_estado_cities[dados_estado_cities.is_last==True]

        st.write(  dia_atual_mapa)
        for feature in data_cities['features']:
            id_city = feature['id']
            dados =dia_atual_mapa[dia_atual_mapa.city_ibge_code == id_city].reset_index().T.rename(columns={0: 'dados'})
            feature['properties'] = dados.to_dict()

        # m = folium.Map(location=[45.5236, -122.6750])
        # html = m.get_root().render()
        # st.markdown(html.encode('utf8'),False)
        #st.write(data_cities)
        # Set the viewport location
        view_state = pdk.ViewState(
            longitude=view[1],
            latitude=view[0],
            zoom=6,
            min_zoom=1,
            max_zoom=60,
            pitch=50,#40.5,
            bearing=0)#-27.36

        geojson = pdk.Layer(
            'GeoJsonLayer',
            data_state,
            opacity=1,
            #stroked=False,
            filled=True,
            #extruded=True,
            #wireframe=True,
            get_fill_color=[255,  255, 255],
            get_line_color=[100, 100, 90],
            #pickable=True
        )

        geojson2 = pdk.Layer(
            'GeoJsonLayer',
            data_cities,
            opacity=0.8,
            stroked=False,
            filled=True,
            extruded=True,
            wireframe=True,
            get_elevation='properties.dados.deaths*1000',
            get_fill_color='[255/2, properties.dados.confirmed  , 255]',
            get_line_color=[0, slide, 255],
            pickable=True
        )
        max_val=1000
        min_val=0

        # Combined all of it and render a viewport
        r = pdk.Deck(layers=[geojson,geojson2],
                     tooltip={"html": f"<b>Color Value:</b> {state}", "style": {"color": "white"}},

                     initial_view_state=view_state,
                     height=800,
                     width=800,
                     map_style="mapbox://styles/mapbox/light-v9",
                     mapbox_key='pk.eyJ1IjoidGVvcmlhIiwiYSI6ImNqODRpNWJrNjA5dGIyd3FoMnZ6am13NjcifQ.OgxGf081lfoKQAOhlYh1Tg'
                     )
        st.pydeck_chart(r)

        dados_estado_melt = pd.melt(
            dados_estado[['date', 'confirmed', 'deaths']],
            id_vars=['date'],
            value_vars=['confirmed', 'deaths'])

        df = dados_estado_melt.groupby(["date", 'variable']).sum().reset_index()

        fig = px.line(df, x="date", y="value", color='variable')

        fig.update_layout(title=f'Casos de Covid em {state}',
                          xaxis_title='Data',
                          yaxis_title='Número de casos')
        st.plotly_chart(fig)
#
# """This app demonstrates the use of the awesome [deck.gl]() framework for visual
# exploratory data analysis of large datasets.
#
# Deck.gl is now (as of Streamlit v. 0.53) supported via the
# [`st.pydeck_chart`](https://docs.streamlit.io/api.html?highlight=pydeck#streamlit.pydeck_chart)
# function.
#
# We use data from the
# [Global Power Plant Database](http://datasets.wri.org/dataset/globalpowerplantdatabase) to
# illustrate the locations, fuel types and capacities of the worlds power plants.
# """
#
#
# import pathlib
#
# import pandas as pd
# import pydeck as pdk
# import streamlit as st
#
# POWER_PLANT_PATH = (
#     pathlib.Path.cwd() / "gallery/global_power_plant_database/global_power_plant_database.csv"
# )
#
# POWER_PLANT_URL = (
#     "https://raw.githubusercontent.com/MarcSkovMadsen/awesome-streamlit/master/"
#     "gallery/global_power_plant_database/global_power_plant_database.csv"
# )
#
# LATITUDE_COLUMN = "latitude"
# LONGITUDE_COLUMN = "longitude"
#
# LOCATIONS = {
#     "Orsted Copenhagen HQ": {"latitude": 55.676098, "longitude": 12.568337},
#     "Orsted Boston": {"latitude": 2.361145, "longitude": -71.057083},
# }
# ORSTED_CPH_HQ = LOCATIONS["Orsted Copenhagen HQ"]
#
# FUEL_COLORS = {
#     "Oil": "black",
#     "Solar": "green",
#     "Gas": "black",
#     "Other": "gray",
#     "Hydro": "blue",
#     "Coal": "black",
#     "Petcoke": "black",
#     "Biomass": "green",
#     "Waste": "green",
#     "Cogeneration": "gray",
#     "Storage": "orange",
#     "Wind": "green",
# }
#
# COLORS_R = {"black": 0, "green": 0, "blue": 0, "orange": 255, "gray": 128}
#
# COLORS_G = {"black": 0, "green": 128, "blue": 0, "orange": 165, "gray": 128}
#
# COLORS_B = {"black": 0, "green": 0, "blue": 255, "orange": 0, "gray": 128}
#
#
# class ViewStateComponent:
#     """Component to let the user set the initial view state to for example Copenhagen or Boston"""
#
#     def __init__(self):
#         self.latitude = ORSTED_CPH_HQ["latitude"]
#         self.longitude = ORSTED_CPH_HQ["longitude"]
#         self.zoom = 1
#         self.pitch = 40.0
#
#     def edit_view(self):
#         """Lets the user edit the attributes"""
#         location = st.sidebar.selectbox("Location", options=list(LOCATIONS.keys()), index=0)
#         self.latitude = LOCATIONS[location]["latitude"]
#         self.longitude = LOCATIONS[location]["longitude"]
#
#         self.zoom = st.sidebar.slider("Zoom", min_value=0, max_value=20, value=self.zoom)
#         self.pitch = st.sidebar.slider(
#             "Pitch", min_value=0.0, max_value=100.0, value=self.pitch, step=10.0
#         )
#
#     @property
#     def view_state(self) -> pdk.ViewState:
#         """The ViewState according to the attributes
#
#         Returns:
#             pdk.ViewState -- [description]
#         """
#         return pdk.ViewState(
#             longitude=self.longitude,
#             latitude=self.latitude,
#             zoom=self.zoom,
#             min_zoom=0,
#             max_zoom=15,
#             pitch=self.pitch,
#             # bearing=-27.36,
#         )
#
#
# class GlobalPowerPlantDatabaseApp:
#     """The main app showing the Global Power Plant Database"""
#
#     def __init__(self):
#         self.view_state_component = ViewStateComponent()
#         self.data = self.get_data()
#         self.show_data = False
#
#     @staticmethod
#     @st.cache
#     def get_data() -> pd.DataFrame:
#         """The Global Power Plant data
#
#         Returns:
#             pd.DataFrame -- The Global Power Plant data cleaned and transformed
#         """
#         try:
#             data = pd.read_csv(POWER_PLANT_PATH)
#         except FileNotFoundError:
#             data = pd.read_csv(POWER_PLANT_URL)
#
#         # Clean
#         data.primary_fuel = data.primary_fuel.fillna("NA")
#         data.capacity_mw = data.capacity_mw.fillna(1)
#
#         # Transform
#         data["primary_fuel_color"] = data.primary_fuel.map(FUEL_COLORS)
#         data["primary_fuel_color"] = data["primary_fuel_color"].fillna("gray")
#         data["color_r"] = data["primary_fuel_color"].map(COLORS_R)
#         data["color_g"] = data["primary_fuel_color"].map(COLORS_G)
#         data["color_b"] = data["primary_fuel_color"].map(COLORS_B)
#         data["color_a"] = 140
#
#         return data[
#             [
#                 "capacity_mw",
#                 LATITUDE_COLUMN,
#                 LONGITUDE_COLUMN,
#                 "primary_fuel_color",
#                 "color_r",
#                 "color_g",
#                 "color_b",
#                 "color_a",
#             ]
#         ]
#
#     def _scatter_plotter_layer(self):
#         return pdk.Layer(
#             "ScatterplotLayer",
#             data=self.data,
#             get_position=[LONGITUDE_COLUMN, LATITUDE_COLUMN],
#             get_fill_color="[color_r, color_g, color_b, color_a]",
#             get_radius="capacity_mw*10",
#             pickable=True,
#             opacity=0.8,
#             stroked=False,
#             filled=True,
#             wireframe=True,
#         )
#
#     def _deck(self):
#         return pdk.Deck(
#             map_style="mapbox://styles/mapbox/light-v9",
#             initial_view_state=self.view_state_component.view_state,
#             layers=[self._scatter_plotter_layer()],
#             tooltip={"html": "<b>Color Value:</b> {primary_fuel}", "style": {"color": "white"}},
#         )
#
#     def view(self):
#         """Main view of the app"""
#         # self.view_state_component.edit_view() # Does not work
#         st.write(__doc__)
#
#         st.pydeck_chart(self._deck())
#
#         st.write(
#             """The maps shows the power plant
#
# - **location** by latitude, longitude coordinates
# - **fuel type** by color and
# - **capacity in MW** by bubble size
# """
#         )
#         st.json(FUEL_COLORS)
#
#         st.write(
#             """Unfortunately **tooltips are not supported**. And there are also other issues.
# See
#
# - [Issue 984](https://github.com/streamlit/streamlit/issues/984)
# - [Issue 985](https://github.com/streamlit/streamlit/issues/985)"""
#         )
#
#
# APP = GlobalPowerPlantDatabaseApp()
# APP.view()
Exemple #9
0
layer = pdk.Layer(
    "TextLayer",
    df,
    pickable=True,
    get_position="coordinates",
    get_text="name",
    get_size=16,
    get_color=[255, 255, 255],
    get_angle=0,
    # Note that string constants in pydeck are explicitly passed as strings
    # This distinguishes them from columns in a data set
    get_text_anchor=String("middle"),
    get_alignment_baseline=String("center"),
)

# Set the viewport location
view_state = pdk.ViewState(latitude=37.7749295,
                           longitude=-122.4194155,
                           zoom=10,
                           bearing=0,
                           pitch=45)

# Render
r = pdk.Deck(
    layers=[layer],
    initial_view_state=view_state,
    tooltip={"text": "{name}\n{address}"},
    map_style=pdk.map_styles.SATELLITE,
)
r.to_html("text_layer.html", notebook_display=False)
df_id = df[[
    'start_latitude', 'start_longitude', 'end_latitude', 'end_longitude'
]]
midpoint = (np.average(df_id["end_latitude"]),
            np.average(df_id["end_longitude"]))

#mapbox used for the arc plot map
st.pydeck_chart(
    pdk.Deck(map_style='mapbox://styles/mapbox/light-v9',
             initial_view_state=pdk.ViewState(
                 latitude=midpoint[0],
                 longitude=midpoint[1],
                 zoom=11,
                 pitch=50,
             ),
             layers=[
                 pdk.Layer(
                     "ArcLayer",
                     data=df_id,
                     get_source_position="[start_longitude, start_latitude]",
                     get_target_position="[end_longitude, end_latitude]",
                     get_source_color=[0, 30, 87, 160],
                     get_target_color=[0, 30, 190, 160])
             ]))

#This section of the first part contains a map that shows the costumer engagement
# Data is taken from the csv files
# What the code does, is that it takes all the costumer engagement from all the days they have been active
#and shows the activity in each hour

#Mapping
my_dataset = 'journey_locations.csv'  # for this plot we take the data from the journey locations
Exemple #11
0
    return z


df_line['coordinates'] = coordinate_dummy
df_line['color'] = df_line['line_name'].apply(make_color)
df_line['weight'] = df_line['line_name'].apply(take_weight)

#Render

line_layer = pdk.Layer(
    'PathLayer',
    df_line,
    get_path='coordinates',
    get_width='weight',
    get_color='[color[0],color[1],color[2]]',
)

point_layer = pdk.Layer('ScatterplotLayer',
                        df_merge,
                        get_position='[X좌표,Y좌표]',
                        get_radius=20,
                        get_fill_color='[255,255,255]',
                        pickable=True,
                        auto_highlight=True)

center = [126.9825876, 37.5377887]
view_state = pdk.ViewState(longitude=center[0], latitude=center[1], zoom=10)

r = pdk.Deck(layers=[line_layer, point_layer], initial_view_state=view_state)
r.to_html("bus_line_data_visulation.html")
Exemple #12
0
def main():
    # Menu
    menu = ['EDA', 'Interactive Charts', 'Prediction', 'About']
    choices = st.sidebar.selectbox('Select Menu', menu)

    # load dataframe
    data = load_data('data/data.csv')
    # we established from EDA that year post 2013 is more stable and more reflective of
    # current market trends
    data2013 = data.query('year_sold >=2013')

    # When 'EDA' is selected at the menu.
    if choices == 'EDA':

        st.title('EDA')

        st.header("Project Title : HDB Price Prediction ML App")
        st.subheader(" Problem Statement")
        st.markdown(
            'How do flat buyers know if they have snatched a good deal?\
        Alternatively, how do flat sellers benchmark their property reasonably?\
        In order to help flat buyers and flat sellers make an informed decision, we decided to find out more about resale flat prices in Singapore.\
        Ultimately, we want to predict the price of resale flats in Singapore.'
        )

        st.markdown(
            'Complete notebook can be found [here](https://nbviewer.jupyter.org/github/andrewng88/hdb/blob/master/2_Exploratory_Data_Analysis.ipynb)'
        )

        st.subheader("The Data")
        st.markdown(
            'Obtained from [Data.gov.sg](http://data.gov.sg/dataset/resale-flat-prices)\
        the dataset is from **1990 to 2019**.')

        if st.checkbox("Show Summary of the Dataset"):
            st.write(data.describe())

        # display overall hdb price trend chart
        table1 = data.groupby("year_sold")["resale_price"].agg(
            ["median"]).reset_index()
        table1.rename(columns={"median": "resale_price"}, inplace=True)
        resale_price = px.line(table1, x="year_sold", y="resale_price")
        resale_price.update_layout(
            title_text='HDB Resale Price trend (1990 - 2019)',
            template='ggplot2')
        st.plotly_chart(resale_price)

        # chart commentary
        st.markdown(
            'The decline in resale price and sudden surge in the number of units sold following 1997 is due to the 1997\
        [Asian financial crisis](https://www.todayonline.com/singapore/divergent-hdb-resale-private-home-price-trends-will-not-last).\
        With regards to the sharp spike in 2007 is because HDB has stopped Walk-In-Selection and replace it with Sale of Balance Flats\
        which is only twice per year and hence everyone went with the Resale')

        # display overall hdb transactions trend chart
        table2 = data.groupby(
            "year_sold")["resale_price"].count().reset_index()
        table2 = table2.rename(columns={"resale_price": "number_of_resale"})
        resale_transaction = px.line(table2,
                                     x="year_sold",
                                     y="number_of_resale")
        resale_transaction.update_layout(
            title_text='HDB Resale Transactions between (1990 - 2019)',
            template='ggplot2')
        st.plotly_chart(resale_transaction)

        # chart commentary
        st.markdown(
            'Implementation of the revised [cooling measures](https://www.srx.com.sg/cooling-measures) to cool the residential market from 2010 onwards\
        led to the drop in resale price and low number of units sold during this period.Specifically the lowering of LTV(Loan-To-Value) from \
        90% to 80% - meaning buyers have to pay more initally.')

        # display overall dollar per square meter based on flat type
        data['dollar_psf'] = data['resale_price'] / (data['floor_area_sqm'] *
                                                     10.764)
        table3 = data.groupby(["year_sold", 'flat_type'
                               ])["dollar_psf", ].agg(["median"
                                                       ]).reset_index()
        table3.rename(columns={"median": "dollar_psf"}, inplace=True)
        dollar_per_sq_f = px.line(table3,
                                  x="year_sold",
                                  y="dollar_psf",
                                  color='flat_type')
        dollar_per_sq_f.update_layout(
            title_text=
            'Median Dollar Per Square Feet between 1990 and 2019 based on flat type',
            template='ggplot2')
        st.plotly_chart(dollar_per_sq_f)

        # chart commentary
        st.markdown(
            'Similar trend if we break down based on flat type, the median went up by two fold from 2007 to 2013 and gradually\
        went down because of additional cooling measures')

        # display overall dollar per square meter based on storey
        table4 = data.groupby(["year_sold", 'storey_range'
                               ])["dollar_psf", ].agg(["median"
                                                       ]).reset_index()
        table4.rename(columns={"median": "dollar_psf"}, inplace=True)
        median_storey = px.line(table4,
                                x="year_sold",
                                y="dollar_psf",
                                color='storey_range')
        median_storey.update_layout(
            title_text=
            'Median Dollar Per Square Feet between 1990 and 2019 based on storey',
            template='ggplot2')
        st.plotly_chart(median_storey)

        st.markdown(
            'Similar trend if we break down based on storey, but for high storey more than 40, price is still climbing.\
        We can also notice that high rise flats ( > 30 storeys ) starts from around 2005 onwards( less 3 years)'
        )

        st.markdown(
            '**We decided to work with data from 2013**. This is because the 1997 Asian financial crisis is a once off event and does not provide an \
        accurate reflection of the current situation.In addition, with the cooling measures still in place, using data from 2013\
        will ensure consistency in this aspect.')

        st.subheader(
            'Complete notebook can be found [here](https://nbviewer.jupyter.org/github/andrewng88/hdb/blob/master/2_Exploratory_Data_Analysis.ipynb)'
        )

    # When 'Interactive Charts' is selected at the menu.

    if choices == 'Interactive Charts':
        st.title('Interactive Charts')

        # 3D map component
        st.subheader("HDB Transactions Visualized using 3D")
        # from 1990 to 2019, defaults to 2019
        year = st.slider('Year to look at', 1990, 2019, 2019)
        data = data[data['year_sold'] == year]

        st.markdown("HDB transactions in **%i**" % (year))
        midpoint = (np.average(data["latitude"]),
                    np.average(data["longitude"]))
        st.write(
            pdk.Deck(
                map_style="mapbox://styles/mapbox/light-v9",
                #display the mid of SG
                initial_view_state={
                    "latitude": midpoint[0],
                    "longitude": midpoint[1],
                    "zoom": 11,
                    "pitch": 50,
                },
                #displays the GPS of each HDB based on year_sold, GPS
                layers=[
                    pdk.Layer("HexagonLayer",
                              data=data[['year_sold', 'latitude',
                                         'longitude']],
                              get_position=["longitude", "latitude"],
                              auto_highlight=True,
                              radius=100,
                              extruded=True,
                              pickable=True,
                              elevation_scale=4,
                              elevation_range=[0, 1000]),
                ],
            ))

        #displays the Median price by Flat type

        st.subheader('View HDB Median price by Flat type')
        flat_type_values = sorted(list(data['flat_type'].unique()))
        flat_type_values.insert(0, 'ALL')
        flat_option = st.selectbox("Flat_type", flat_type_values)
        sort_option = st.radio("Sort by", ("Ascending", "Descending"))
        flat_type_display_text = f'<sup>You selected {flat_option} and {sort_option}</sup>'
        st.markdown(flat_type_display_text, unsafe_allow_html=True)

        sort_option_dict = {
            'Ascending': False,
            'Descending': True,
        }

        if flat_option == 'ALL':
            revenue_all = data.groupby(
                ['town'])['resale_price'].median().reset_index().sort_values(
                    by=['resale_price'],
                    ascending=sort_option_dict[sort_option])
            figure_to_plot = revenue_all
        else:
            revenue = data[data['flat_type'] == flat_option]
            revenue = revenue.groupby(
                ['town'])['resale_price'].median().reset_index().sort_values(
                    by=['resale_price'],
                    ascending=sort_option_dict[sort_option])
            figure_to_plot = revenue
        fig_median = px.bar(figure_to_plot,
                            x='resale_price',
                            y='town',
                            orientation="h",
                            height=600,
                            template='ggplot2')
        fig_median_title = f'HDB Median price for {flat_option} flats in {sort_option} order'
        fig_median.update_layout(title_text=fig_median_title)
        st.plotly_chart(fig_median)

        #displays the Median price by MRT

        st.subheader('View HDB Median price by MRT')
        mrt_values = sorted(list(data2013['mrt'].unique()))
        mrt_values.insert(0, 'ALL')
        mrt_option = st.selectbox("MRT", mrt_values)
        mrt_display_text = f'<sup>You selected {mrt_option}</sup>'
        st.markdown(mrt_display_text, unsafe_allow_html=True)

        if mrt_option == 'ALL':
            mrt_all = data2013.query('nearest_mrt_distance <1').groupby(
                ['mrt'])['resale_price'].median().reset_index().sort_values(
                    by=['resale_price'])
            fig_median = px.bar(mrt_all,
                                x='resale_price',
                                y='mrt',
                                orientation='h',
                                height=600,
                                template='ggplot2')
            st.write(mrt_all)
        else:
            mrt = data2013[data2013['mrt'] == mrt_option]
            mrt = mrt.query('nearest_mrt_distance <1').groupby([
                'mrt', 'flat_type'
            ])['resale_price'].median().reset_index().sort_values(
                by=['resale_price']).drop('mrt', axis=1)
            fig_median = px.bar(mrt,
                                x='flat_type',
                                y='resale_price',
                                height=400,
                                template='ggplot2')
            fig_median_title = f'HDB Median price for HDB flats near {mrt_option}'
            fig_median.update_layout(title_text=fig_median_title)
        st.plotly_chart(fig_median)

    # When 'Prediction' is selected at the menu.

    if choices == 'Prediction':
        st.subheader('Predictions')

        # load the unique database for speed
        df_unique_deploy = load_data('data/df_unique_deploy.csv')

        #obtain Postcode input from end user
        input_postcode = st.text_input("Postcode : ", 560216)  #560216
        postcode_list = df_unique_deploy['postcode'].unique().tolist()

        # we proceed with HDB transaction prediction, if the postcode is in the list
        if int(input_postcode) in postcode_list:

            input_postcode_results = f"Postcode is **{input_postcode}** "

            #auto retrieve the flat_type for selection based on postcode
            flat_type = df_unique_deploy[df_unique_deploy['postcode'] == int(
                input_postcode)]['flat_type'].unique().tolist()
            flat_type = st.selectbox("The flat_type", (flat_type))
            flat_type_results = f"Flat Type is **{flat_type}**."

            #auto retrieve the flat_model for selection based on postcode
            f_model = df_unique_deploy[df_unique_deploy['postcode'] == int(
                input_postcode)]['flat_model'].unique().tolist()
            flat_model = st.selectbox("The flat_model", (f_model))
            flat_model_results = f"Flat Model is **{flat_model}**."

            #auto retrieve town for selection based on postcode
            town = df_unique_deploy[df_unique_deploy['postcode'] == int(
                input_postcode)]['town'].unique()[0]
            town_results = f" and it is located in **{town }** town ."

            #storey requires input from end user as we're not mind reader :P
            storey = st.slider("Storey level : ", 1, 50, 6)  #8
            storey_results = f"Storey is **{storey}**."

            #auto retrieve floor_area_sqm for selection based on postcode
            area = df_unique_deploy[df_unique_deploy['postcode'] == int(
                input_postcode)]['floor_area_sqm'].unique().tolist()
            floor_area_sqm = st.selectbox("Floor_area_sqm", (area))
            area_results = f"Area is **{floor_area_sqm }**."

            # calculate remaining lease = start year + 99 - current year
            today = date.today()
            year_sold = today.year
            month_sold = today.month
            lease_commence_date = df_unique_deploy[
                df_unique_deploy['postcode'] == int(
                    input_postcode)]['lease_commence_date'].tolist()[0]
            remaining_lease = int(lease_commence_date) + 99 - year_sold
            remaining_lease_results = f"Remaining lease is **{remaining_lease}** years ."

            #auto retrieve nearest_mrt_distance for selection based on postcode
            nearest_mrt_distance = df_unique_deploy[
                df_unique_deploy['postcode'] == int(input_postcode)][
                    'nearest_mrt_distance'].unique().tolist()[0]
            nearest_mrt_distance_results = f"MRT is **{nearest_mrt_distance:.2f}** km away."

            #auto retrieve CBD_distance for selection based on postcode
            CBD_distance = df_unique_deploy[
                df_unique_deploy['postcode'] == int(
                    input_postcode)]['CBD_distance'].unique().tolist()[0]
            cbd_distance_results = f"CBD is **{CBD_distance:.2f}** km away."

            #auto retrieve nearest_mall_distance for selection based on postcode
            nearest_mall_distance = df_unique_deploy[
                df_unique_deploy['postcode'] == int(input_postcode)][
                    'nearest_mall_distance'].unique().tolist()[0]
            nearest_mall_distance_results = f"Nearest Mall is **{nearest_mall_distance:.2f}** km away."

            #auto retrieve nearest_school_distance
            nearest_school_distance = df_unique_deploy[
                df_unique_deploy['postcode'] == int(input_postcode)][
                    'nearest_school_distance'].unique().tolist()[0]
            nearest_school_distance_results = f"Nearest school is **{nearest_school_distance:.2f}** km away."

            #condolidate all data for prediction
            sample_data = [[
                floor_area_sqm, year_sold, month_sold, remaining_lease,
                nearest_mrt_distance, CBD_distance, nearest_mall_distance,
                nearest_school_distance, storey, town, flat_type, flat_model
            ]]

            list_columns = [
                'floor_area_sqm', 'year_sold', 'month_sold', 'remaining_lease',
                'nearest_mrt_distance', 'CBD_distance',
                'nearest_mall_distance', 'nearest_school_distance', 'storey',
                'town', 'flat_type', 'flat_model'
            ]

            sample_data = pd.DataFrame(sample_data, columns=list_columns)

            #load model and predict
            predictor = load_prediction_models('data/rf.sav')
            predictor.predict(sample_data)

            #display data input
            if st.checkbox('Verbose ON/OFF:'):
                st.markdown(input_postcode_results + town_results)
                st.markdown(flat_type_results)
                st.markdown(flat_model_results)
                st.markdown(storey_results)
                st.markdown(area_results)
                st.markdown(remaining_lease_results)
                st.markdown(nearest_mrt_distance_results)
                st.markdown(cbd_distance_results)
                st.markdown(nearest_mall_distance_results)
                st.markdown(nearest_school_distance_results)
                st.write('Data collated for prediction:')
                st.write(sample_data)

            #prefix $ and convert prediction to int
            prediction = "{} {}".format('$',
                                        int(predictor.predict(sample_data)))
            st.subheader('HDB valuation:')
            st.success(prediction)

            #display other HDB data from the same block
            st.subheader(
                "Other transactions from 2013 onwards(sorted by latest transaction)"
            )
            st.dataframe(data2013[data2013['postcode']==int(input_postcode)].sort_values(by='month', ascending=False)\
            [['resale_price','dollar_psf','month','flat_type','flat_model','storey_range','lease_commence_date','floor_area_sqm']])

        #message to display if Postcode does not exists
        else:
            st.warning('Please input valid Postcode')

    if choices == 'About':
        st.header('About')

        st.subheader('Project by:')
        st.markdown('**Andrew Ng** [email protected]')
        st.markdown('https://www.linkedin.com/in/sc-ng-andrew/')
        st.markdown('**Lau Lee Ling** [email protected]')
        st.markdown('https://www.linkedin.com/in/lauleeling/')
Exemple #13
0
 pdk.Deck(
     map_style="mapbox://styles/mapbox/satellite-streets-v11",
     initial_view_state=computed_view,
     layers=[
         pdk.Layer(
             "ScatterplotLayer",
             data=load_data.locationdf,
             get_position="[longitude, latitude]",
             get_color="[200, 30, 0, 190]",
             get_line_color="[0, 0, 0]",
             stroked=True,
             filled=True,
             radius_min_pixels=30,
             lineWidthMinPixels=4,
             pickable=True,
             extruded=True,
         ),
         pdk.Layer(
             "TextLayer",
             load_data.locationdf,
             pickable=True,
             get_position="[longitude, latitude]",
             get_text="id",
             get_size=25,
             get_color=[256, 256, 256],
             # Note that string constants in pydeck are explicitly passed as strings
             # This distinguishes them from columns in a data set
             get_text_anchor=String("middle"),
             get_alignment_baseline=String("center"),
         ),
     ],
     tooltip={
         "html": "<b>Meetkastje: {id}</b>",
         "style": {
             "color": "white"
         }
     },
 ))
Exemple #14
0
polygon_layer = pydeck.Layer(
    "PolygonLayer",
    df,
    id="geojson",
    opacity=0.8,
    stroked=False,
    get_polygon="coordinates",
    filled=True,
    extruded=True,
    wireframe=True,
    get_elevation="elevation",
    get_fill_color="fill_color",
    get_line_color=[255, 255, 255],
    auto_highlight=True,
    pickable=True,
)

tooltip = {
    "html":
    "<b>Value per Square Meter:</b> {valuePerSqm} <br /><b>Growth rate:</b> {growth}"
}

r = pydeck.Deck(
    polygon_layer,
    initial_view_state=view_state,
    effects=[lighting_effect],
    map_style="mapbox://styles/mapbox/light-v9",
    tooltip=tooltip,
)
r.to_html("polygon_layer.html", notebook_display=False)
Exemple #15
0
CPU_GRID_LAYER_DATA = (
    "https://raw.githubusercontent.com/uber-common/"
    "deck.gl-data/master/website/sf-bike-parking.json"
)
df = pd.read_json(CPU_GRID_LAYER_DATA)

# Define a layer to display on a map

layer = pdk.Layer(
    "GridLayer",
    df,
    pickable=True,
    extruded=True,
    cell_size=200,
    elevation_scale=4,
    get_position="COORDINATES",
)

view_state = pdk.ViewState(
    latitude=37.7749295, longitude=-122.4194155, zoom=11, bearing=0, pitch=45
)

# Render
r = pdk.Deck(
    layers=[layer],
    initial_view_state=view_state,
    tooltip={"text": "{position}\nCount: {count}"},
)
r.to_html("grid_layer.html")
Exemple #16
0
    "255 * (1 - (start[2] / 10000))",
]

scatterplot = pydeck.Layer(
    "ScatterplotLayer",
    DATA_URL["AIRPORTS"],
    radius_scale=20,
    get_position="coordinates",
    get_fill_color=[255, 140, 0],
    get_radius=60,
    pickable=True,
)

line_layer = pydeck.Layer(
    "LineLayer",
    DATA_URL["FLIGHT_PATHS"],
    get_source_position="start",
    get_target_position="end",
    get_color=GET_COLOR_JS,
    get_width=10,
    highlight_color=[255, 255, 0],
    picking_radius=10,
    auto_highlight=True,
    pickable=True,
)

layers = [scatterplot, line_layer]

r = pydeck.Deck(layers=layers, initial_view_state=INITIAL_VIEW_STATE)
r.to_html("line_layer.html", notebook_display=False)
Exemple #17
0
    # This distinguishes them from columns in a data set
    get_text_anchor="'middle'",
    get_alignment_baseline="'center'",
)

# Set the viewport location
view_state = pdk.ViewState(latitude=37.7749295,
                           longitude=-122.4194155,
                           zoom=10,
                           bearing=0,
                           pitch=45)

# Render
r = pdk.Deck(
    layers=[layer],
    initial_view_state=view_state,
    map_style=pdk.map_styles.SATELLITE,
)

app = dash.Dash(__name__)

app.layout = html.Div(
    dash_deck.DeckGL(
        r.to_json(),
        id="deck-gl",
        tooltip={"text": "{name}\n{address}"},
        mapboxKey=mapbox_api_token,
    ))

if __name__ == "__main__":
    app.run_server(debug=True)
Exemple #18
0
    df = pd.DataFrame(np.random.randn(x, 2) / [50, 50] + [37.76, -122.4],
                      columns=['latitude', 'longitude'])
    st.pydeck_chart(
        pdk.Deck(
            map_style='mapbox://styles/mapbox/light-v9',
            initial_view_state=pdk.ViewState(
                latitude=37.76,
                longitude=-122.4,
                zoom=11,
                pitch=50,
            ),
            layers=[
                pdk.Layer(
                    'Hexagonlayer',
                    data=df,
                    get_position='[longitude, latitude]',
                    radius=200,
                    elevation_scale=4,
                    elevation_range=[0, 1000],
                    pickable=True,
                    extruded=True,
                ),
                pdk.Layer('ScatterplotLayer',
                          data=df,
                          get_position='[longitude, latitude]',
                          get_color='[200,30,0,160]',
                          get_radius=200),
            ],
        ))

if option == "Deck gl Chart":
    s = st.sidebar.slider("Set x", 1, 1000, 1)
st.markdown("Vehicle Collisions between %i:00 and %i:00" % (hour,
                                                            (hour + 1) % 24))
midpoint = (np.average(data['latitude']), np.average(data['longitude']))

st.write(
    pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",
        initial_view_state={
            'latitude': midpoint[0],
            'longitude': midpoint[1],
            'zoom': 11,
            'pitch': 50,
        },
        layers=[
            pdk.Layer(
                'HexagonLayer',
                data=data[['date/time', 'latitude', 'longitude']],
                get_position=['longitude', 'latitude'],
                radius=100,
                extruded=True,
                pickable=True,
                elevation_scalr=4,
                elevation_range=[0, 1000],
            ),
        ],
    ))

st.subheader('Breakdown by Minute between %i:00 and %i:00' % (hour,
                                                              (hour + 1) % 24))

filtered = data[(data['date/time'].dt.hour >= hour)
df3['lng'] = df3['lng'].astype('float')
df3['lat'] = df3['lat'].astype('float')
df3 = df3.rename(columns={'lng': 'lon'})

df_map = df3[['lat', 'lon']]

st.pydeck_chart(
    pdk.Deck(
        map_style='mapbox://styles/mapbox/light-v9',
        initial_view_state=pdk.ViewState(
            latitude=42.36,
            longitude=-90.06,
            zoom=3,
        ),
        layers=[
            pdk.Layer(
                'ScatterplotLayer',
                data=df_map,
                get_position='[lon, lat]',
                get_color='[50, 158, 168, 70]',
                get_radius=15000,
            ),
        ],
    ))

##2 show the number of protests across the country by state and date
st.subheader("The number of protests in each state by date")
st.markdown("""
Peaks of protests occurred mainly on weekends. This makes sense because most Americans have more free time on the weekends and do not have to work during this time. 
After the data’s maximum on June 6th, we noticed that the protests seem to be dwindling down. 
However, a resurgence of protests occurred on June 19th, otherwise known as Juneteenth. 
Exemple #21
0
def main():
    st.set_page_config(layout="wide") 
    st.markdown('<style>#vg-tooltip-element{z-index: 1000051}</style>',
             unsafe_allow_html=True)

    confirmed_df, death_df, recovery_df = wwConfirmedDataCollection()
    st.title("Covid-19 ­Ъда Pandemic Data Visualization")
    displayRawData(confirmed_df, death_df, recovery_df)
    confirmed_df, death_df, recovery_df = dataMassaging(
        confirmed_df, death_df, recovery_df
    )
    full_table = mergeDataAndDataCorrection(confirmed_df, death_df, recovery_df)

    st.write('\nData from "CSSEGISandData POST data massaging"')
    
    user_selectionbox_input = st.selectbox(
        "Select an option", ["Global", "Select from list of countries"]
    )
    min_date_found = full_table["date"].min()
    max_date_found = full_table["date"].max()

    selected_date = st.date_input(
        "Pick a date",
        (min_date_found, max_date_found)
    )
    if len(selected_date) == 2:
        
        if user_selectionbox_input == "Select from list of countries":
            full_table = full_table[(full_table['date'] >= selected_date[0]) & (full_table['date'] <= selected_date[1])]
            
            # full_table = full_table[full_table["date"] == (between(selected_date[0], selected_date[1]))]
            list_of_countries = full_table["location"].unique()
            selected_country = st.selectbox("Select country", list_of_countries)

            mask_countries = full_table["location"] == (selected_country)
            full_table = full_table[mask_countries]

            # Adding new cases to the table for graphing
            full_table["new_confirmed"] = full_table["confirmed"].diff(1).fillna(0)
            full_table["new_recovered"] = full_table["recovered"].diff(1).fillna(0)
            full_table["new_deaths"] = full_table["deaths"].diff(1).fillna(0)
            

            user_input = st.selectbox(
                "Select an option", ["Total Number of Cases", "New Cases Per Day"]
            )
            st.write(full_table)
            if user_input == "New Cases Per Day":
                source = pd.DataFrame(full_table, columns=["date", "new_confirmed", "new_recovered", "new_deaths"])
                title = f"New Cases Per Day for {selected_country}"
            else:
                source = pd.DataFrame(
                    full_table, columns=["date", "confirmed", "deaths", "recovered"]
                )
                title = f"Total reported cases for {selected_country}"
            
            st.altair_chart(altairLineChartGraphing(title, source), use_container_width=True)    

        else:
            full_table = full_table[full_table["date"] == selected_date[1]]
            confirmed_source = pd.DataFrame(full_table, columns=["location", "lat", "lon", "confirmed"])
            

            #Readable values
            confirmed_source["confirmed_readable"] = confirmed_source["confirmed"].apply(human_format)
            display_confirmed_source = pd.DataFrame(confirmed_source, columns=["location", "lat", "lon", "confirmed_readable"]).reset_index(drop=True)
            display_confirmed_source = display_confirmed_source.rename(columns={"confirmed_readable": "confirmed"})
            st.dataframe(display_confirmed_source)

            INITIAL_VIEW_STATE = pdk.ViewState(
                latitude=55.3781,
                longitude=-3.436,
                zoom=1,
                pitch=25,
            )

            column_layer = pdk.Layer(
                "ColumnLayer",
                data=confirmed_source,
                get_position=["lon", "lat"],
                radius=50000,
                get_elevation="confirmed",
                elevation_scale=0.25,
                get_fill_color=["255,255, confirmed*.01"],
                get_line_color=[255, 255, 255],
                filled=True,
                pickable=True,
                extruded=True,
                auto_highlight=True,
            )
            TOOLTIP = {
                "html": "{location}<br> <b>{confirmed_readable}</b> Confirmed Cases",
                "style": {
                    "background": "grey",
                    "color": "white",
                    "font-family": '"Helvetica Neue", Arial',
                    "z-index": "10000",
                },
            }

            r = pdk.Deck(
                column_layer,
                map_style="mapbox://styles/mapbox/satellite-streets-v11",
                map_provider="mapbox",
                initial_view_state=INITIAL_VIEW_STATE,
                tooltip=TOOLTIP,
            )
            st.write("## Total Number of Confirmed Cases All Time")
            st.pydeck_chart(r)
    else:
        st.write("Select Valid Dates to continue")
Exemple #22
0
st.markdown("O objetivo desse mapa é ajudar pequenos e " +
            "médios empresários a fazer um marketing mais eficiente " +
            "e mais barato baseado em quais regiões forem melhor " +
            "para anunciar o seu produto.")

point = [zenvia_csv['latitude'][0], zenvia_csv['longitude'][0]]
st.write(
    pdk.Deck(map_style="mapbox://styles/mapbox/light-v9",
             initial_view_state={
                 "latitude": point[0],
                 "longitude": point[1],
                 "zoom": 11,
                 "pitch": 50,
             },
             layers=[
                 pdk.Layer(
                     "ColumnLayer",
                     data=zenvia_csv,
                     get_position=["longitude", "latitude"],
                     auto_highlight=True,
                     radius=100,
                     extruded=True,
                     pickable=True,
                     get_elevation='500*lead_score',
                     get_fill_color=[
                         "(5-lead_score)*(10-lead_score)*10",
                         "(3-lead_score)*(10-lead_score)*(-1)*10",
                         "(3-lead_score)*(5-lead_score)*10"
                     ],
                 ),
             ]))
def main():
    ### Dataframe must be loaded before any maps
    # file_path = "gs://{}/{}".format(BUCKET_NAME, PRETEST_PATH)
    data = pd.read_csv(
        "streamlit_prep/predicted_reviews.csv")  #updatekey predicted_reviews
    data = data.drop(
        columns=['manually_added_emotion', 'joy, sad, worry, anger, neutral'])
    data.rename(columns={'lng': 'lon'}, inplace=True)
    data.fillna('nan', inplace=True)

    # define emoji
    JOY_URL = "https://res.cloudinary.com/dq7pjfkgz/image/upload/v1606418659/joy_gabpby.png"
    SAD_URL = "https://res.cloudinary.com/dq7pjfkgz/image/upload/v1606418659/sad_icpf1w.png"
    WORRY_URL = "https://res.cloudinary.com/dq7pjfkgz/image/upload/v1606418659/worry_rwobfs.png"
    ANGER_URL = "https://res.cloudinary.com/dq7pjfkgz/image/upload/v1606418659/angry_shqypp.png"
    NEUTRAL_URL = "https://res.cloudinary.com/dq7pjfkgz/image/upload/v1606418659/neutral_evi6qa.png"
    joy_icon = {
        "url": JOY_URL,
        "width": 242,
        "height": 242,
        "anchorY": 242,
    }
    sad_icon = {
        "url": SAD_URL,
        "width": 242,
        "height": 242,
        "anchorY": 242,
    }
    worry_icon = {
        "url": WORRY_URL,
        "width": 242,
        "height": 242,
        "anchorY": 242,
    }
    anger_icon = {
        "url": ANGER_URL,
        "width": 242,
        "height": 242,
        "anchorY": 242,
    }
    neutral_icon = {
        "url": NEUTRAL_URL,
        "width": 242,
        "height": 242,
        "anchorY": 242,
    }

    # split dataframe to emotions
    joy_df = data[data['emotion'] == 'joy']  #updatekey
    joy_df["emoji"] = None
    for i in joy_df.index:
        joy_df["emoji"][i] = joy_icon

    sad_df = data[data['emotion'] == 'sad']  #updatekey
    sad_df["emoji"] = None
    for i in sad_df.index:
        sad_df["emoji"][i] = sad_icon

    worry_df = data[data['emotion'] == 'worry']  #updatekey
    worry_df["emoji"] = None
    for i in worry_df.index:
        worry_df["emoji"][i] = worry_icon

    anger_df = data[data['emotion'] == 'anger']  #updatekey
    anger_df["emoji"] = None
    for i in anger_df.index:
        anger_df["emoji"][i] = anger_icon

    neutral_df = data[data['emotion'] == 'neutral']  #updatekey
    neutral_df["emoji"] = None
    for i in neutral_df.index:
        neutral_df["emoji"][i] = neutral_icon

    # analysis = st.sidebar.selectbox("Choose your map", ["Data spread", "All-in-one", "Joy", "Sad", "Worry", "Neutral" "Unknown?!"])
    # if analysis == "Data spread":
    if st.checkbox('Data spread'):
        st.header("Dots on the map")
        st.markdown("this is a placeholder text")
        st.map(data=data)

    if st.checkbox('All-in-one'):
        st.pydeck_chart(
            pdk.Deck(
                map_style='mapbox://styles/mapbox/streets-v11',
                initial_view_state=pdk.ViewState(
                    latitude=51.50722,
                    longitude=-0.1275,
                    zoom=9,
                    pitch=50,
                ),
                layers=[
                    pdk.Layer(
                        type="IconLayer",
                        data=joy_df,
                        get_icon="emoji",
                        get_size=3,
                        size_scale=15,
                        get_position=["lon", "lat"],
                    ),
                    pdk.Layer(
                        type="IconLayer",
                        data=sad_df,
                        get_icon="emoji",
                        get_size=3,
                        size_scale=15,
                        get_position=["lon", "lat"],
                    ),
                    pdk.Layer(
                        type="IconLayer",
                        data=worry_df,
                        get_icon="emoji",
                        get_size=3,
                        size_scale=15,
                        get_position=["lon", "lat"],
                    ),
                    pdk.Layer(
                        type="IconLayer",
                        data=anger_df,
                        get_icon="emoji",
                        get_size=3,
                        size_scale=15,
                        get_position=["lon", "lat"],
                    ),
                    pdk.Layer(
                        type="IconLayer",
                        data=neutral_df,
                        get_icon="emoji",
                        get_size=3,
                        size_scale=15,
                        get_position=["lon", "lat"],
                    ),
                ],
            ))

    if st.checkbox('joy'):
        st.pydeck_chart(
            pdk.Deck(
                map_style='mapbox://styles/mapbox/dark-v10',
                initial_view_state=pdk.ViewState(
                    latitude=51.50722,
                    longitude=-0.1275,
                    zoom=9,
                    pitch=50,
                ),
                layers=[
                    pdk.Layer(
                        'HexagonLayer',
                        data=data,  #updatekey
                        get_position='[lon, lat]',
                        radius=200,
                        elevation_scale=8,
                        elevation_range=[0, 2000],
                        get_fill_color='[0, 128, 255, 160]',
                        #pickable=True,
                        extruded=True,
                    ),
                    pdk.Layer(
                        'ScatterplotLayer',
                        data=data,  #updatekey
                        get_position='[lon, lat]',
                        get_color='[200, 30, 0, 160]',
                        # get_color='[0, 128, 255, 160]',
                        get_radius=200,
                    ),
                ],
            ))

        ### Button for google map outer link #https://discuss.streamlit.io/t/how-to-link-a-button-to-a-webpage/1661/4
        joyest = joy_df['place_id'].value_counts().index.tolist()[0]
        address = f"https://www.google.com/maps/place/?q=place_id:{joyest}"
        link = f'[Let\'s find out the most joyful place in London]({address})'
        st.markdown(link, unsafe_allow_html=True)

    if st.checkbox('Sad'):
        st.pydeck_chart(
            pdk.Deck(
                map_style='mapbox://styles/mapbox/dark-v10',
                initial_view_state=pdk.ViewState(
                    latitude=51.50722,
                    longitude=-0.1275,
                    zoom=9,
                    pitch=50,
                ),
                layers=[
                    pdk.Layer(
                        'HeatmapLayer',
                        data=data,  #updatekey
                        get_position='[lon, lat]',
                        get_color='[0, 128, 255, 160]',
                        get_radius=100,
                    ),
                ],
            ))
        sadest = sad_df['place_id'].value_counts().index.tolist()[0]
        address = f"https://www.google.com/maps/place/?q=place_id:{sadest}"
        link = f'[Let\'s find out the most depressive place in London]({address})'
        st.markdown(link, unsafe_allow_html=True)

    if st.checkbox("Guess my mood"):
        # take user input
        default = "Type something"
        text = st.text_area("Talk to me", default)
        text_df = {'Text': [text]}

        # convert user input to DF and clean
        text_df = pd.DataFrame(text_df)
        clean_text = clean_data(text_df)
        text_value = clean_text['tokenized_text']

        # load tokenizer locally
        with file_io.FileIO('streamlit_prep/models_tokenizer_model_tokenizer',
                            'rb') as handle:
            tokenizer = pickle.load(handle)

        # numericalise user input text
        max_seq_len = 300
        index_of_words = tokenizer.word_index
        vocab_size = len(index_of_words) + 1
        sequence_text = tokenizer.texts_to_sequences(text_value)
        text_pad = pad_sequences(sequence_text, maxlen=max_seq_len)

        # prediction
        model = load_model('streamlit_prep/models_emotions_v2_saved_model.pb')
        preds = model.predict(text_pad)

        # prep results for presentation
        angry = str(round(preds[0][0] * 100, 2))
        joy = str(round(preds[0][1] * 100, 2))
        worry = str(round(preds[0][2] * 100, 2))
        neutral = str(round(preds[0][3] * 100, 2))
        sad = str(round(preds[0][4] * 100, 2))

        # presentation
        st.write(f"Joy: {joy}%")
        st.write(f"Worry: {worry}%")
        st.write(f"Sad: {sad}%")
        st.write(f"Neutral: {neutral}%")
        st.write(f"Angry: {angry}%")
Exemple #24
0
    get_line_color=covid_colour,
)

# Configure the tooltip
tooltip_value = {
    "html": "Flight {number} from {origin_country} to {destination_country}",
    'style': {
        'color': 'white',
        'background': 'black'
    }
}

# Create the deck.gl map
r = pdk.Deck(
    layers=[covid_layer, flight_layer],
    initial_view_state=view,
    map_style="mapbox://styles/mapbox/dark-v9",
    #map_style = "https://s3.amazonaws.com/cdn.brianbancroft.io/assets/osmstyle.json",
    tooltip=tooltip_value)

# Create Covid chart
# Trim covid data frame to period interested in
covid_subset = covid_data[covid_data["date"] <= datetime.datetime(2020, 3, 31)]

# Get maximum value for selected covid "measure" - required for line chart
max_value = covid_subset.groupby("date")[covid_measure].sum().max()

# Bar chart of "measure" by Country - Didin't look that great
#covid_cases_chart = alt.Chart(covid_subset).transform_aggregate(
#    max_value = "max(" + covid_measure + ")", groupby = ["Country"]
#).transform_window(
#    rank = "rank(max_value)",
Exemple #25
0
df = pd.read_json(S2_LAYER_DATA)

# Define a layer to display on a map
layer = pdk.Layer(
    "S2Layer",
    df,
    pickable=True,
    wireframe=False,
    filled=True,
    extruded=True,
    elevation_scale=1000,
    getS2Token="token",
    get_fill_color="[value * 255, (1 - value) * 255, (1 - value) * 128]",
    get_elevation="value",
)

# Set the viewport location
view_state = pdk.ViewState(latitude=37.7749295,
                           longitude=-122.4194155,
                           zoom=11,
                           bearing=0,
                           pitch=45)

# Render
r = pdk.Deck(
    layers=[layer],
    initial_view_state=view_state,
    tooltip={"text": "{token} value: {value}"},
)
r.to_html("s2_layer.html", notebook_display=False)
Exemple #26
0
if st.sidebar.checkbox("Ver tabela com dados"):
    st.header("Raw Data")
    st.write(df)

df.time = pd.to_datetime(df.time)
ano_selecionado = st.sidebar.slider("Selecione um ano", 2010, 2018, 2015)
df_selected = df[df.time.dt.year == ano_selecionado]

# st.map(df_selected)
# mapa
st.subheader("Mapa da Criminalidade")
# st.map(df)
st.pydeck_chart(
    pdk.Deck(
        initial_view_state=pdk.ViewState(latitude=-23.567145,
                                         longitude=-46.648936,
                                         zoom=8,
                                         pitch=50),
        layers=[
            pdk.Layer('HexagonLayer',
                      data=df_selected[['latitude', 'longitude']],
                      get_position='[longitude,latitude]',
                      auto_highlight=True,
                      elevation_scale=50,
                      pickable=True,
                      elevation_range=[0, 3000],
                      extruded=True,
                      coverage=1)
        ],
    ))
Exemple #27
0
            <td>{room_type}</td>
        <tr>
        <tr>
            <th>Price:</th>
            <td>${price}</td>
        <tr>
        <tr>
            <th>Neighbourhood:</th>
            <td>{neighbourhood}</td>
        <tr>
    </table>
"""
st.pydeck_chart(
    pdk.Deck(
        layers=[scatter],
        initial_view_state=view_state,
        tooltip={'html': tooltip},
    ))

'## Bar Chart'
stacked_bar_chart = alt.Chart(filtered_data).transform_aggregate(
    count='count()', groupby=['neighbourhood', 'room_type']).mark_bar().encode(
        alt.X('neighbourhood:N', sort='-y', title='Neighbourhood'),
        alt.Y('count:Q', title='Number of Airbnbs'),
        color=alt.Color('room_type', legend=alt.Legend(title='Room type')),
        tooltip=['count:Q', 'room_type', 'neighbourhood']).interactive()
st.altair_chart(stacked_bar_chart)

if st.checkbox('Show filtered raw data'):
    '## Filterd Raw Data'
    filtered_data
Exemple #28
0
def main():
    api_key = '02f23d8e1dd050539725ce70b158e81bf6416cec'
    val = ['gasolina_93', 'gasolina_97', 'gasolina_95', 'petroleo_diesel']
    data = load_data(val, api_key)

    ##titulo inicial de la pagina
    st.title("Precios de Combustibles")

    ## Comienzo de las 3 etapas de la pagina
    if data is not None:  ##consulta si existen datos

        data.to_csv('precios_bencinas.csv')  #guarda los datos en un archivo
        H = grafo(data)  #LLama a la funcion Grafo
        #nx.draw(H)
        #plt.show()

        T = arbol(H)

        datos_arbol = conectorG(T)

        peso_arbol = pesoA(T)

        datosTo_mapa = conectors_H(H)

        st.markdown(
            "Esta es una aplicacion web para monitorear precios de combustibles"
        )

        option = st.selectbox(
            'Que tipo de combustible desea revisar?',
            val)  #llamada al creador de la casilla de seleccion
        st.write('You selected:', option)
        sns.catplot(x="id_region", y=option, kind="bar", data=data)
        st.pyplot()  ##llamdo de streamlit hacia pyplot para generar la grafica
        #fin de la generacion de la grafica

        #comienzo del mapa
        st.write('Mapa representarivo de geolocalizacion de vencineras\n')
        midpoint = (-20.25879, -70.13311
                    )  #situa el mapa en la primera region a trabajar
        ##generador del mapa
        r=pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",##selecciona el formato del mapa
        initial_view_state={##selecciona vista inicial del mapa
            "latitude": midpoint[0],
            "longitude": midpoint[1],
            "zoom": 13,
            "pitch": 50,
        },
        layers=[##genera una capa para agregar figuras o popup en el mapa
            pdk.Layer(
            "HexagonLayer",
            data=data[[option, 'lat', 'lon']],##obtiene la longitud y latitud de cada vencinera
            get_position=["lon", "lat"],##situa la generacion en la ubicacion obtenida antes 
            auto_highlight=True,
            radius=20,##radio del objeto generado
            extruded=True,
            pickable=True
            ),

            ##nuevo layer que permite la generacion de lineas
            pdk.Layer(#las lineas se generan con un inicio y fin 
            "LineLayer",
            data = datos_arbol, #si se quiere mostrar el grafo en el mapa, solo debe reemplazar "datos_arbol" por "datosTo_mapa"
            get_source_position = "start",
            get_target_position = "end",
            picking_radius=8,
            get_width=2,
            get_color=255,
            highlight_color=[255, 255, 0],
            auto_highlight=True,
            pickable=True,
            ),
        ],
        tooltip=True
        )
        st.write(r)  ##escribe el mapa con su respectivos objetos en la pagina
        #fin del mapa
        st.write('El recorrido del arbol representa ' + str(peso_arbol) +
                 'km\n')

        ##top de precios (al final de la pagina)
        st.header("Top 5 Precios")
        values = np.unique(data['id_region'].cat.categories)
        options = np.unique(data['region'].cat.categories)

        region = st.selectbox('Seleccione region', options)
        st.bar_chart(data.loc[data['region'] == region][val].sort_values(
            by=[option], ascending=False)[:5])

        #fin del top 5 precios

    else:
        ##mensaje en el caso de que los datos no sean cargados
        st.markdown("Esta aplicacion no esta disponible en este momento")
Exemple #29
0
def mission(dataset):
    parameters = [1, 2, 3, 4, 5, 6, 7]
    water_parameters = {
        1: "Total Water Column (m)",
        2: "Temperature (c)",
        3: "pH",
        4: "ODO mg/L",
        5: "Salinity (ppt)",
        6: "Turbid+ NTU",
        7: "BGA-PC cells/mL"
    }
    selected_parameters = [water_parameters.get(key) for key in parameters]

    def selectDataframe(dataset: str, selected_parameters: List[str]):
        entire_ds = pd.read_csv(
            dataset, delimiter=';')  # read the entire dataset as a dataframe
        # print(entire_ds.columns) #to print the head of the dataframe
        mission_date = entire_ds.at[2, 'Date']

        selected_parameters.insert(0, "Latitude")
        selected_parameters.insert(1, "Longitude")
        selected_parameters.insert(2, "Time hh:mm:ss")

        try:
            partial_ds = entire_ds[selected_parameters]
            print("The dataframe was successfully created!")
            print(partial_ds.columns)  # to print the head of the dataframe
            partial_ds = partial_ds.rename(columns={
                "Latitude": "lat",
                "Longitude": "lon"
            })
            return partial_ds, mission_date
        except ValueError:
            print(
                "Oops!  Some selected water parameters do not exist in this dataset. Try again..."
            )

    partial_ds = selectDataframe(
        dataset, selected_parameters)[0]  # calling function selectDataframe
    min_turb = partial_ds[["Turbid+ NTU"]].min()
    partial_ds[["Turbid+ NTU"]] = partial_ds[["Turbid+ NTU"]] - min_turb

    st.title('Biscayne Bay Missions')

    st.header("Data Collection - " +
              selectDataframe(dataset, selected_parameters)[1])

    st.subheader("Summary Table")
    options = st.multiselect('Select Desired Parameters', [
        "Total Water Column (m)", "Temperature (c)", "pH", "ODO mg/L",
        "Salinity (ppt)", "Turbid+ NTU", "BGA-PC cells/mL"
    ])

    # st.write('You selected:', options[0])

    partial_ds[['lat', 'lon'] + options]

    see_stats = st.checkbox('Click here for descriptive statistics')
    if see_stats:
        st.subheader("Descriptive Statistics Table")
        st.dataframe(partial_ds[[
            "Total Water Column (m)", "Temperature (c)", "pH", "ODO mg/L",
            "Salinity (ppt)", "Turbid+ NTU", "BGA-PC cells/mL"
        ]].describe())

    st.subheader("Map")
    # st.map(partial_ds[['lat','lon']])

    st.pydeck_chart(
        pdk.Deck(
            map_style='mapbox://styles/mapbox/streets-v11',
            # map_style='mapbox://styles/mapbox/light-v9',
            initial_view_state=pdk.ViewState(
                latitude=25.91275783,
                longitude=-80.13782367,
                zoom=16,
                pitch=50,
            ),
            layers=[
                # pdk.Layer(
                #    'HexagonLayer',
                #    data=partial_ds[['lat','lon']],
                #    get_position='[lon, lat]',
                #    radius=10,
                #    elevation_scale=4,
                #    elevation_range=[0, 1000],
                #    pickable=True,
                #    extruded=True,
                # ),
                pdk.Layer(
                    'ScatterplotLayer',
                    data=partial_ds[['lat', 'lon']],
                    get_position='[lon, lat]',
                    get_color='[200, 30, 0, 160]',
                    get_radius=1,
                ),
            ],
        ))
Exemple #30
0
                       stroked=True,
                       filled=True,
                       radius_scale=10,
                       radius_min_pixels=2,
                       radius_max_pixels=25,
                       line_width_min_pixels=1,
                       get_position=["lon", "lat"],
                       get_radius='Casos',
                       get_fill_color=[252, 136, 3],
                       get_line_color=[255, 0, 0],
                       tooltip="test test")

# Create the deck.gl map
r = pdk.Deck(
    layers=[covidLayer],
    initial_view_state=view,
    map_style="mapbox://styles/mapbox/light-v10",
)

map = st.pydeck_chart(r)

# Create a subheading to display current date
subheading = st.subheader("Tendencia de casos confirmados")

# Render the deck.gl map in the Streamlit app as a Pydeck chart

mostrar2 = data.copy()
if len(paises) > 0:
    mostrar2 = mostrar2[mostrar2.Pais.isin(paises)]

c = alt.Chart(