Exemple #1
0
hour = st.slider("Hour to look at", 0, 23)

data = data[data[DATE_TIME].dt.hour == hour]

st.subheader("Geo data between %i:00 and %i:00" % (hour, (hour + 1) % 24))
midpoint = (np.average(data["lat"]), np.average(data["lon"]))
st.deck_gl_chart(
    viewport={
        "latitude": midpoint[0],
        "longitude": midpoint[1],
        "zoom": 11,
        "pitch": 50,
    },
    layers=[
        {
            "type": "HexagonLayer",
            "data": data,
            "radius": 100,
            "elevationScale": 4,
            "elevationRange": [0, 1000],
            "pickable": True,
            "extruded": True,
        }
    ],
)

st.subheader("Breakdown by minute between %i:00 and %i:00" % (hour, (hour + 1) % 24))
filtered = data[
    (data[DATE_TIME].dt.hour >= hour) & (data[DATE_TIME].dt.hour < (hour + 1))
]
hist = np.histogram(filtered[DATE_TIME].dt.minute, bins=60, range=(0, 60))[0]
Exemple #2
0
# data=df,
# get_position='[longitude, latitude]',
# get_color='[200, 30, 0, 160]',
# get_radius=100,
# ),
# ],
# )
# )

st.deck_gl_chart(viewport={
    'latitude': lat_avg,
    'longitude': lng_avg,
    'zoom': 11,
    'pitch': 0,
},
                 layers=[{
                     'type': 'ScatterplotLayer',
                     'data': df,
                     'radiusScale': 5,
                     'radiusMinPixels': 5,
                     'getFillColor': [248, 24, 148],
                 }])

##############################################################
## reduce columns and print
displayed_columns = [
    'week', 'date', 'event_name', 'region', 'location', 'day_night',
    'national', 'map', 'club', 'event_link', 'deadline'
]
df = df[displayed_columns]
st.deck_gl_chart(
    viewport={
        "latitude": 37.76,
        "longitude": -122.4,
        "zoom": 11,
        "pitch": 50
    },
    layers=[
        {
            # Plot number of bike rentals throughtout the city
            "type": "HexagonLayer",
            "data": bike_rental_stats,
            "radius": 200,
            "elevationScale": 4,
            "elevationRange": [0, 1000],
            "pickable": True,
            "extruded": True,
        },
        {
            # Now plot locations of Bart stops
            # ...and let's size the stops according to traffic
            "type": "ScatterplotLayer",
            "data": bart_stop_stats,
            "radiusScale": 10,
            "getRadius": 50,
        },
        {
            # Now Add names of Bart stops
            "type": "TextLayer",
            "data": bart_stop_stats,
            "getText": "name",
            "getColor": [0, 0, 0, 200],
            "getSize": 15,
        },
        {
            # And draw some arcs connecting the stops
            "type": "ArcLayer",
            "data": bart_path_stats,
            "pickable": True,
            "autoHighlight": True,
            "getStrokeWidth": 10,
        },
    ],
)
Exemple #4
0
})

spec = {
    'mark': 'line',
    'encoding': {
        'x': {'field': 'a', 'type': 'quantitative'},
        'y': {'field': 'b', 'type': 'quantitative'},
    },
}

# 2 empty charts
st.vega_lite_chart(spec)
st.pyplot()

# 1 empty map
st.deck_gl_chart()

# 10 errors
try:
    st.vega_lite_chart({})
except Exception as e:
    st.write(e)

try:
    st.vega_lite_chart(data, {})
except Exception as e:
    st.write(e)

try:
    st.vega_lite_chart(data)
except Exception as e:
Exemple #5
0
import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
                  columns=["lat", "lon"])

# TODO: Use this instead of the example below. Need to autodetect viewport
# first, thought.
# st.deck_gl_chart(df)

st.deck_gl_chart(
    viewport={
        "latitude": 37.76,
        "longitude": -122.4,
        "zoom": 11,
        "pitch": 50
    },
    layers=[{
        "type": "ScatterplotLayer",
        "data": df
    }],
)
Exemple #6
0
st.deck_gl_chart(
    viewport={
        'latitude': 37.76,
        'longitude': -122.4,
        'zoom': 11,
        'pitch': 50,
    },
    layers=[
        {
            # Plot number of bike rentals throughtout the city
            'type': 'HexagonLayer',
            'data': bike_rental_stats,
            'radius': 200,
            'elevationScale': 4,
            'elevationRange': [0, 1000],
            'pickable': True,
            'extruded': True,
        },
        {
            # Now plot locations of Bart stops
            # ...and let's size the stops according to traffic
            'type': 'ScatterplotLayer',
            'data': bart_stop_stats,
            'radiusScale': 10,
            'getRadius': 50,
        },
        {
            # Now Add names of Bart stops
            'type': 'TextLayer',
            'data': bart_stop_stats,
            'getText': 'name',
            'getColor': [0, 0, 0, 200],
            'getSize': 15,
        },
        {
            # And draw some arcs connecting the stops
            'type': 'ArcLayer',
            'data': bart_path_stats,
            'pickable': True,
            'autoHighlight': True,
            'getStrokeWidth': 10,
        }
    ])
st.deck_gl_chart(
    viewport={
        "latitude": 40.78, 
        "longitude": -73.97,
        "zoom": 11,
        "pitch": 50,
    },
    layers=[
        {
            "type": "ArcLayer",
            "data": data,
            "encoding":{
                "getColorR": flowColors[0][0],
            "getColorG":flowColors[0][1],
            "getColorB":flowColors[0][2],
            "getTargetColorR": flowColors[0][0],
            "getTargetColorG":flowColors[0][1],
            "getTargetColorB":flowColors[0][2],
                "getLatitude":{"field":"lat"},
                "getLongitude":{"field":"lon"},
                "getTargetLatitude":{"field":"lat2"},
                "getTargetLongitude":{"field":"lon2"},
            
            },
            
            # "radius": 100,
            # "elevationScale": 4,
            # "elevationRange": [0, 1000],
            # "pickable": True,
            # "extruded": True,
        }
    ],
)
Exemple #8
0
def mapping_demo():
    import pandas as pd

    @st.cache
    def from_data_file(filename):
        url = ("https://raw.githubusercontent.com/streamlit/"
               "streamlit/develop/examples/data/%s" % filename)
        return pd.read_json(url)

    try:
        ALL_LAYERS = {
            "Bike Rentals": {
                "type": "HexagonLayer",
                "data": from_data_file("bike_rental_stats.json"),
                "radius": 200,
                "elevationScale": 4,
                "elevationRange": [0, 1000],
                "pickable": True,
                "extruded": True,
            },
            "Bart Stop Exits": {
                "type": "ScatterplotLayer",
                "data": from_data_file("bart_stop_stats.json"),
                "radiusScale": 0.05,
                "getRadius": "exits",
            },
            "Bart Stop Names": {
                "type": "TextLayer",
                "data": from_data_file("bart_stop_stats.json"),
                "getText": "name",
                "getColor": [0, 0, 0, 200],
                "getSize": 15,
            },
            "Outbound Flow": {
                "type": "ArcLayer",
                "data": from_data_file("bart_path_stats.json"),
                "pickable": True,
                "autoHighlight": True,
                "getStrokeWidth": 10,
                "widthScale": 0.0001,
                "getWidth": "outbound",
                "widthMinPixels": 3,
                "widthMaxPixels": 30,
            }
        }
    except urllib.error.URLError as e:
        st.error("""
            **This demo requires internet access.**

            Connection error: %s
        """ % e.reason)
        return

    st.sidebar.markdown('### Map Layers')
    selected_layers = [
        layer for layer_name, layer in ALL_LAYERS.items()
        if st.sidebar.checkbox(layer_name, True)
    ]
    if selected_layers:
        viewport = {
            "latitude": 37.76,
            "longitude": -122.4,
            "zoom": 11,
            "pitch": 50
        }
        st.deck_gl_chart(viewport=viewport, layers=selected_layers)
    else:
        st.error("Please choose at least one layer above.")
Exemple #9
0
import numpy as np
import pandas as pd

np.random.seed(12345)

data = np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4]
df = pd.DataFrame(data, columns=["lat", "lon"])

# Test for scatterplot basic charts:
#   st.deck_gl_chart(viewport=viewport_dict, layers=layers_list).

viewport = {"latitude": 37.76, "longitude": -122.4, "zoom": 11, "pitch": 50}

layers = [{"data": df, "type": "ScatterplotLayer"}]

st.deck_gl_chart(viewport=viewport, layers=layers)

# Test a similar chart but with a full dict spec:
#   st.deck_gl_chart(spec=spec_dict)
spec = {
    "viewport": {
        "latitude": 37.76,
        "longitude": -122.4,
        "zoom": 11,
        "pitch": 50
    },
    "layers": [{
        "data": df,
        "type": "ScatterplotLayer",
        "radius": 250,
        "extruded": True
Exemple #10
0
def plot_map(data):
    h = st.deck_gl_chart(viewport={
        "latitude": midpoint[0],
        "longitude": midpoint[1],
        "zoom": 11,
        "pitch": 0
    },
                         layers=[{
                             'id': "scat-blue",
                             'type': 'ScatterplotLayer',
                             'data': data[data.comuna == 'Las Condes'],
                             'opacity': 0.5,
                             'getColor': [75, 205, 250],
                             'pickable': True,
                             'autoHighlight': True,
                             'getRadius': 10,
                             'radiusMinPixels': 1,
                         }, {
                             'id': 'scat-red',
                             'type': 'ScatterplotLayer',
                             'data': data[data.comuna == 'Providencia'],
                             'opacity': 0.5,
                             'getColor': [255, 94, 87],
                             'autoHighlight': True,
                             'pickable': True,
                             'getRadius': 10,
                             'radiusMinPixels': 1,
                         }, {
                             'id': 'scat-green',
                             'type': 'ScatterplotLayer',
                             'data': data[data.comuna == 'Santiago'],
                             'opacity': 0.5,
                             'getColor': [50, 205, 50],
                             'autoHighlight': True,
                             'pickable': True,
                             'getRadius': 10,
                             'radiusMinPixels': 1,
                         }, {
                             'id': 'scat-purple',
                             'type': 'ScatterplotLayer',
                             'data': data[data.comuna == 'Ñuñoa'],
                             'opacity': 0.5,
                             'getColor': [138, 43, 226],
                             'autoHighlight': True,
                             'pickable': True,
                             'getRadius': 10,
                             'radiusMinPixels': 1,
                         }, {
                             'id': 'scat-orange',
                             'type': 'ScatterplotLayer',
                             'data': data[data.comuna == 'Recoleta'],
                             'opacity': 0.5,
                             'getColor': [255, 165, 0],
                             'autoHighlight': True,
                             'pickable': True,
                             'getRadius': 10,
                             'radiusMinPixels': 1,
                         }, {
                             'id': 'scat-pink',
                             'type': 'ScatterplotLayer',
                             'data': data[data.comuna == 'Vitacura'],
                             'opacity': 0.5,
                             'getColor': [255, 108, 180],
                             'autoHighlight': True,
                             'pickable': True,
                             'getRadius': 10,
                             'radiusMinPixels': 1,
                         }, {
                             'id':
                             'scat-brown',
                             'type':
                             'ScatterplotLayer',
                             'data':
                             data[data.comuna == 'Estación Central'],
                             'opacity':
                             0.5,
                             'getColor': [139, 69, 19],
                             'autoHighlight':
                             True,
                             'pickable':
                             True,
                             'getRadius':
                             10,
                             'radiusMinPixels':
                             1,
                         }])
    return h
day_filtered = df.loc[df['dag van de week'] == days[day]]

lus_filtered = day_filtered.loc[day_filtered['lus'] == lus]

nonlussen = df.loc[df['lus'] != lus]
lussie = df.loc[df['lus'] == lus]

st.deck_gl_chart(viewport={
    'latitude': nonlussen.groupby('lus').first()['lat'][2],
    'longitude': nonlussen.groupby('lus').first()['lon'][2],
    'zoom': 12,
    'pitch': 50,
},
                 layers=[
                     {
                         'data': nonlussen.groupby('lus').first(),
                         'type': 'ScatterPlotLayer',
                         'radius': 100
                     },
                     {
                         'data': lussie.groupby('lus').first(),
                         'type': 'ScatterPlotLayer',
                         'radius': 300,
                         'getColor': [75, 205, 250]
                     },
                 ])

st.bar_chart(lus_filtered['Intensiteit'])
st.bar_chart(lus_filtered['Gemiddelde snelheid'])
    def inicializar(self, app=app_hub()):

        opcoes = [
            'Quantidade de valores nao preenchidos',
            'Porcetagem de dados faltantes por coluna'
        ]
        dados, lista = app.carregar(self.path)

        #Exercicio 01 valores vazios
        if self.option == app.dicionario[0]:
            self.option_01 = st.radio('Exercicio 01: Escolha o grafico:',
                                      opcoes)
            st.write(
                'Para cada coluna identique a quantidade de linhas com dados faltantes (em alguns casos, o dado faltante é uma string vazia, em outros casos é uma string contendo algum valor do tipo: "sem informação"). Faça um método que retorna a média de dados faltantes por coluna'
            )
            if self.option_01 == opcoes[0]:
                st.markdown('### Valores vazios ou faltantes: ')
                st.bar_chart(app.count_nulls(lista))
                #st.bar_chart(dados)
                if st.checkbox('Mostrar lista de dados faltantes'):
                    #st.write(app.count_nulls(app.construir(app.linhas)))
                    st.write(app.count_nulls(lista))

            if self.option_01 == opcoes[1]:
                st.markdown('### Porcetagem de valores faltantes por coluna: ')
                #st.bar_chart(app.media_nulls(app.count_nulls(app.construir(app.linhas))))
                st.bar_chart(app.media_nulls(app.count_nulls(lista), dados))
                if st.checkbox('Mostrar lista de porcetagem'):
                    st.write(
                        list(
                            app.media_nulls(
                                app.count_nulls(app.construir(self.path)))))

        #Exercicio 02 Nivel taxonomico
        if self.option == app.dicionario[1]:
            st.write(
                'Para cada item identifique até qual nível taxônomico a ocorrência foi identificada.'
            )
            #verificaTaxonomia metodo importado do felipe
            st.bar_chart(verificaTaxonomia(app.construir(self.path)))
            #st.bar_chart(verificaTaxonomia(app.construir(lista)))
            if st.checkbox('Valores por Coluna'):
                st.write(verificaTaxonomia(app.construir(self.path)))

        #chama o nível taxonomico do mais geral, Reino (1), até o mais específico, Espécie (7)
        #def taxonomicRank(self):
        #	c = lista #era a minha self.stringList() que chamava uma lista onde cada entrada é uma string do csv
        #	rank = []
        #	for i in range(1,len(c)):
        #	    for j in range(21, 14, -1):
        #		if c[i][j] != 'Sem Informações':
        #		    break
        #	    rank.append(j-14)
        #	return rank

        #Exercicio 03  Filtros
        if self.option == app.dicionario[2]:

            mapa_bio = pd.read_csv(self.path)
            mapa_bio.rename(columns={
                'Latitude': 'lat',
                'Longitude': 'lon'
            },
                            inplace=True)

            st.write(
                'Monte filtros de ocorrências por estados, nome de espécie (nome exato ou parte do nome) e categoria de ameaça, e outros filtros que julgar relevante.'
            )
            lista_de_filtros = [
                'Municipio', 'Familia', 'Filo', 'Classe', 'Localidade',
                'Nome cientifico'
            ]
            filtros = st.multiselect(
                "Escolha os filtros: -> Municipio -> Familia -> Filo -> Classe -> Localidade -> Nome cientifico",
                lista_de_filtros)

            data = pd.DataFrame()
            f1, f2, f3, f4, f5, f6 = 1, 1, 1, 1, 1, 1

            if filtros:
                my_bar = st.progress(0)
                for percent_complete in range(0, 100):
                    my_bar.progress(percent_complete + 1)

            for item in filtros:
                if item == 'Municipio':
                    municipios = st.multiselect(
                        'Escolha os municipios',
                        list(set(mapa_bio['Municipio'])))  #, ["Londrina"]
                    if not municipios:
                        f1 = 1
                    else:
                        f1 = mapa_bio['Municipio'].isin(municipios)

                if item == 'Familia':
                    familias = st.multiselect('Escolha a familia',
                                              list(set(mapa_bio['Familia'])))
                    if not familias:
                        f2 = 1
                    else:
                        f2 = mapa_bio['Familia'].isin(familias)

                if item == 'Filo':
                    filos = st.multiselect('Escolha o Filo',
                                           list(set(mapa_bio['Filo'])))
                    if not filos:
                        f3 = 1
                    else:
                        f3 = mapa_bio['Filo'].isin(filos)

                if item == 'Classe':
                    classes = st.multiselect('Escolha a classe',
                                             list(set(mapa_bio['Classe'])))
                    if not classes:
                        f4 = 1
                    else:
                        f4 = mapa_bio['Classe'].isin(classes)

                if item == 'Localidade':
                    localidades = st.multiselect(
                        'Escolha Localidade',
                        list(set(mapa_bio['Localidade'])))
                    if not localidades:
                        f5 = 1
                    else:
                        f5 = mapa_bio['Localidade'].isin(localidades)

                if item == 'Nome cientifico':
                    nomes = st.multiselect(
                        'Escolha Nome cientifico',
                        list(set(mapa_bio['Nome cientifico'])))

                    if not nomes:
                        f6 = 1
                    else:
                        f6 = mapa_bio['Nome cientifico'].isin(nomes)

                data = mapa_bio.loc[f1 & f2 & f3 & f4 & f5 & f6]

            st.deck_gl_chart(viewport={
                'latitude': -23.37,
                'longitude': -51.28,
                'zoom': 11,
                'pitch': 50,
            },
                             layers=[{
                                 'type': 'HexagonLayer',
                                 'data': data,
                                 'radius': 200,
                                 'elevationScale': 4,
                                 'elevationRange': [0, 1000],
                                 'pickable': True,
                                 'extruded': True,
                             }, {
                                 'type': 'ScatterplotLayer',
                                 'data': data,
                             }])

            if st.checkbox('Mostrar dados'):
                st.dataframe(data)

        #Exercicio 04 - Geocode - Verificar se dados batem

        if self.option == app.dicionario[3]:
            mapa_bio = pd.read_csv(self.path)
            mapa_bio.rename(columns={
                'Latitude': 'lat',
                'Longitude': 'lon'
            },
                            inplace=True)
            row = np.arange(0, len(mapa_bio))
            loc = []
            for i in row:
                loc.append([mapa_bio["lat"][i], mapa_bio["lon"][i]])
            #locDF = pd.DataFrame(loc,columns=['lat', 'lon'])
            #st.map(locDF)
            #st.write(locDF)
            #
            # #Reverse geocoder (Precisa terminar)
            cities = reverse_geocode.search(
                loc)  #Faz processo reverso e através de lat long traz a cidade
            cities = pd.DataFrame(cities)  #Transforma a lista em dataframe
            #New dataset com lat long e a respectiva cidade
            newdf = mapa_bio[['lat', 'lon', 'Municipio']]
            comparecitiesTrue = []
            comparecitiesFalse = []
            for j in np.arange(0, len(newdf)):
                if newdf['Municipio'][j] != cities['city'][j]:
                    comparecitiesFalse.append([
                        mapa_bio['lat'][j], mapa_bio['lon'][j],
                        mapa_bio['Municipio'][j], cities['city'][j]
                    ])
                if newdf['Municipio'][j] == cities['city'][j]:
                    comparecitiesTrue.append([
                        mapa_bio['lat'][j], mapa_bio['lon'][j],
                        mapa_bio['Municipio'][j], cities['city'][j]
                    ])
            comparecitiesFalse = pd.DataFrame(comparecitiesFalse,
                                              columns=[
                                                  'lat', 'lon',
                                                  'Municipio Planilha',
                                                  'Reverse Geocode'
                                              ])
            comparecitiesTrue = pd.DataFrame(comparecitiesTrue,
                                             columns=[
                                                 'lat', 'lon',
                                                 'Municipio Planilha',
                                                 'Reverse Geocode'
                                             ])
            st.markdown('### Dados com Localização Correta')
            #st.map(comparecitiesTrue[['lat','lon']])
            st.deck_gl_chart(viewport={
                'latitude': -23.37,
                'longitude': -51.28,
                'zoom': 11,
                'pitch': 50,
            },
                             layers=[{
                                 'type': 'HexagonLayer',
                                 'data': comparecitiesTrue[['lat', 'lon']],
                                 'radius': 200,
                                 'elevationScale': 4,
                                 'elevationRange': [0, 1000],
                                 'pickable': True,
                                 'extruded': True,
                             }, {
                                 'type': 'ScatterplotLayer',
                                 'data': comparecitiesTrue[['lat', 'lon']],
                             }])
            if st.checkbox('Mostrar dados corretos:'):
                st.write(comparecitiesTrue.
                         loc[:, ['Municipio Planilha', 'Reverse Geocode']])
            st.markdown('### Dados com Localização Incorreta')
            #st.map(comparecitiesFalse[['lat','lon']])
            st.deck_gl_chart(viewport={
                'latitude': -23.37,
                'longitude': -51.28,
                'zoom': 11,
                'pitch': 50,
            },
                             layers=[{
                                 'type': 'HexagonLayer',
                                 'data': comparecitiesFalse[['lat', 'lon']],
                                 'radius': 200,
                                 'elevationScale': 4,
                                 'elevationRange': [0, 1000],
                                 'pickable': True,
                                 'extruded': True,
                             }, {
                                 'type':
                                 'ScatterplotLayer',
                                 'data':
                                 comparecitiesFalse[['lat', 'lon']],
                             }])
            if st.checkbox('Mostrar dados incorretos:'):
                st.write(comparecitiesFalse.
                         loc[:, ['Municipio Planilha', 'Reverse Geocode']])
Exemple #13
0
    # Adding code so we can have map default to the center of the data
    midpoint = (np.average(data['lat']), np.average(data['lon']))

    st.deck_gl_chart(viewport={
        'latitude': midpoint[0],
        'longitude': midpoint[1],
        'zoom': 4
    },
                     layers=[{
                         'id': "scat-blue",
                         'type': 'ScatterplotLayer',
                         'data': data.iloc[:25],
                         'opacity': 1,
                         'getColor': [75, 205, 250],
                         'pickable': True,
                         'autoHighlight': True,
                         'getRadius': 200,
                         'radiusMinPixels': 5,
                     }, {
                         'id': 'scat-red',
                         'type': 'ScatterplotLayer',
                         'data': data.iloc[25:50],
                         'opacity': 1,
                         'getColor': [255, 94, 87],
                         'autoHighlight': True,
                         'pickable': True,
                         'getRadius': 200,
                         'radiusMinPixels': 5,
                     }])

st.subheader("Display of map using streamlit in-built map method st.map()")
if st.checkbox("Click box to view  sttreamlit map"):
Exemple #14
0
def main():
    st.title('Coronavirus EDA in Web')
    st.sidebar.title('Coronavirus')
    image = Image.open('img.jpg')
    st.sidebar.image(image, caption='Coronaviruse', use_column_width=True)
    st.sidebar.subheader(
        'Coronaviruses (CoV) are a large family of viruses that cause illness ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS-CoV) and Severe Acute Respiratory Syndrome (SARS-CoV). A novel coronavirus (nCoV) is a new strain that has not been previously identified in humans. '
    )

    data = pd.read_csv('data.csv')
    data.rename(columns={
        'Province/State': 'Province_State',
        'Country/Region': 'Country_Region'
    },
                inplace=True)
    data.rename(columns={'Lat': 'lat', 'Long': 'lon'}, inplace=True)
    data = data[[
        'Province_State', 'Country_Region', 'lat', 'lon', 'Date', 'Confirmed',
        'Deaths', 'Recovered', 'geometry'
    ]]
    if st.checkbox("show Data"):
        st.write(data)

    if st.checkbox("Show Head of the data"):
        st.write(data.head())

    if st.checkbox("Check Shape"):
        st.write(data.shape)

    if st.checkbox("Show All Columns name"):
        st.write(data.columns)

    if st.checkbox("Describe Data"):
        st.write(data.describe())

    if st.checkbox("Check Null Values"):
        st.write(data.isna().sum().to_frame().sort_values(
            0).style.background_gradient(cmap='summer_r'))

    st.subheader("Per day (Confirmed, Deaths, and Recovered) Patient")
    if st.checkbox("Check Per Day"):
        df_perday = data.groupby('Date')['Confirmed', 'Deaths',
                                         'Recovered'].max()
        st.write(df_perday)
        st.write(df_perday.plot())
        st.pyplot()

    st.subheader("Group Data by (State and Country Region)")
    if st.checkbox("Group Data"):
        d = data.groupby(['Province_State',
                          'Country_Region'])['Confirmed', 'Deaths',
                                             'Recovered'].max()
        d.style.background_gradient(cmap='Pastel1_r')
        st.write(d)

    st.subheader("Which Country has the most affected people?")
    if st.checkbox("Show "):
        st.write(data['Country_Region'].value_counts().plot(kind='bar',
                                                            figsize=(20, 10)))
        st.pyplot()

    st.subheader(" Most Deaths with respect to Country")
    if st.checkbox("Show Plot"):
        plt.figure(figsize=(20, 10))
        st.write(
            data.groupby(['Country_Region'
                          ])['Deaths'].max().plot(kind='bar',
                                                  figsize=(20, 10)))
        plt.yticks(rotation=45)
        st.pyplot()

    st.subheader("scatter plot between Confirmed and Recovered Patient")
    if st.checkbox("Scatter Plot"):
        st.write(
            sns.relplot(x='Confirmed',
                        y='Recovered',
                        data=data,
                        hue='Recovered'))
        st.pyplot()

    st.subheader("Death with respect to Date")
    if st.checkbox("Death=>Date"):
        plt.figure(figsize=(20, 10))
        plt.xlabel('Deaths')
        plt.ylabel('Date')
        st.write(
            plt.plot(data['Deaths'],
                     data['Date'],
                     c='r',
                     marker='o',
                     linewidth=2))

        st.pyplot()

    st.subheader("Interactive Geographical data visualization")
    if st.checkbox("Visualization"):
        st.deck_gl_chart(viewport={
            'latitude': data['lat'][0],
            'longitude': data['lon'][0],
            'zoom': 4
        },
                         layers=[{
                             'type': 'ScatterplotLayer',
                             'data': data,
                             'radiusScale': 250,
                             'radiusMinPixels': 5,
                             'getFillColor': [248, 24, 148],
                         }])

    st.title("Himanshu Tripathi")
    st.subheader("Thanks For Watching")
Exemple #15
0
    def testDeckGlMap(self, longitude=-0.1252, latitude=51.5315):
        rows = st.slider('Number of data points',
                         min_value=10000,
                         max_value=50000,
                         step=5000,
                         value=10000,
                         key=1)
        spread = st.slider('Spread',
                           min_value=0.0,
                           max_value=1.0,
                           step=0.01,
                           value=0.25,
                           key=1)
        spread /= 10

        # randn generates a standard normal distribution array of shape (D0, D1,    . Dn) with mean=0 and sd=1
        # randn(1000, 2) generates a 1000 rows x 2 cols array of normally distributed data points
        df_map = pd.DataFrame(np.random.randn(rows, 2) * [spread, spread] +
                              [longitude, latitude],
                              columns=['longitude', 'latitude'])

        COLOUR_RANGE = [[29, 53, 87], [69, 123, 157], [168, 218, 220],
                        [241, 250, 238], [239, 35, 60], [217, 4, 41]]

        test_success_outcome = False
        try:
            # HexagonLayer bins its data points within each hex shape bucket
            st.deck_gl_chart(viewport={
                'longitude': longitude,
                'latitude': latitude,
                'zoom': 10,
                'pitch': 55,
            },
                             layers=[{
                                 'id': 'heatmap',
                                 'type': 'HexagonLayer',
                                 'colorRange': COLOUR_RANGE,
                                 'data': df_map,
                                 'getLongitude': 'longitude',
                                 'getLatitude': 'latitude',
                                 'radius': 200,
                                 'coverage': 1,
                                 'upperPercentile': 100,
                                 'elevationScale': 4,
                                 'elevationRange': [0, 1000],
                                 'pickable': True,
                                 'extruded': True,
                                 'opacity': 0.8,
                                 'stroked': False,
                                 'filled': True
                             }, {
                                 'type': 'ScatterplotLayer',
                                 'data': df_map,
                                 'getColor': [209, 162, 30, 160],
                                 'get_radius': 200
                             }])
            test_success_outcome = True
        except:
            st.warning('Can\'t display map with supplied settings')

        st.write('First Longitude = %.4f, First Latitude = %.4f' %
                 (df_map['longitude'].iloc[0], df_map['latitude'].iloc[0]))

        self.assertTrue(test_success_outcome == True)
Exemple #16
0
                                     2021, 10, 6, 12, 10, 20))

data = pd.DataFrame({
    'awesome cities': ["Start", "End"],
    'lat': [start_point[0], end_point[0]],
    'lon': [start_point[1], end_point[1]]
})
st.deck_gl_chart(viewport={
    'latitude': NYC_center_lat,
    'longitude': NYC_center_lon,
    'zoom': 10
},
                 layers=[{
                     'type': 'ScatterplotLayer',
                     'data': data[data.index == 0],
                     'radiusScale': 1,
                     'radiusMinPixels': 6,
                     'getFillColor': [248, 24, 148],
                 }, {
                     'type': 'ScatterplotLayer',
                     'data': data[data.index == 1],
                     'radiusScale': 1,
                     'radiusMinPixels': 6,
                     'getFillColor': [22, 130, 70],
                 }])

key = '2012-10-06 12:10:20.0000001'
pickup_date = st.sidebar.date_input('pickup datetime',
                                    value=datetime.datetime(
                                        2021, 10, 6, 12, 10, 20))
pickup_datetime = f'{pickup_date} {time_var}UTC'
pickup_longitude = start_point[1]
        postal_row = postal_df[postal_df['name'] == row["FSA"]]
        postal_covid['lat'][index] = (postal_row['geom_lat'].values[0])
        postal_covid['lon'][index] = (postal_row['geom_long'].values[0])

    postal_covid['lat'] = postal_covid['lat'].astype(float)
    postal_covid['lon'] = postal_covid['lon'].astype(float)

    # Display the table
st.write(postal_covid)

st.markdown("""
We have the data ready now. We will dislplay it as a map for toronto with multiple points. The radius of the
points will determine the number infections in the FSA.
""")

midpoint = (np.average(postal_covid['lat']), np.average(postal_covid['lon']))

st.deck_gl_chart(viewport={
    'zoom': 10.5,
    'latitude': midpoint[0],
    'longitude': midpoint[1],
    'pitch': 10,
},
                 layers=[{
                     'type': 'ScatterplotLayer',
                     'data': postal_covid,
                     'radiusScale': 2,
                     'radiusMaxPixels': 100,
                     'getRadius': "_id",
                 }])
Exemple #18
0

def query_ip(ips):
    df = pd.DataFrame()
    for ip in ips.split(','):
        ip = ip.strip()
        response = requests.get(f'{API_URL}{ip}?api-key={API_KEY}')
        if response.status_code == 200:
            data = json.loads(response.content)
            df = df.append(pd.DataFrame(pd.io.json.json_normalize(data)))
    return df


st.title('IP Geolocation')
ips = st.text_area('IP addresses separated by comma', '8.8.8.8, 1.1.1.1')

df = query_ip(ips)
st.table(
    df[['ip', 'emoji_flag', 'country_name', 'city', 'asn.name',
        'asn.type']].reset_index())

st.deck_gl_chart(layers=[{
    'data': df,
    'type': 'TextLayer',
    'getText': 'ip',
}, {
    'data': df,
    'type': 'ScatterplotLayer',
    'getRadius': 1e2,
}])
def main():
    st.success(
        "**_Crime Rate Analysis_: Sacramento, California - Jan 2018 Data**")

    image = Image.open('sacramento.jpg')
    st.image(image,
             caption='Sacramento,California (source-wiki)',
             use_column_width=True)

    # Function to load the data and cache it
    @st.cache
    def load_data():
        data = pd.read_csv('california_crimeinfo.csv')
        return data

    # load data and cache it using Streamlit cache
    crime_data = load_data()

    # Create a Check box to display the raw data.
    if st.checkbox('Show raw data'):
        st.subheader('Raw data')
        load_state = st.text('Loading Data..')
        st.write(crime_data)
        load_state.text('Loading Completed!')

    # Create a Check box to show few summary details.
    if st.checkbox('Crime Summary'):
        grp_data = crime_data.copy()
        grp_data['Count'] = 1
        st.subheader('Top 50 Crimes in a Month')
        st.write(
            pd.DataFrame(
                grp_data.groupby(['C_Descrip'],
                                 sort=False)['Count'].count().rename_axis(
                                     ["Type of Crime"]).nlargest(50)))
        st.subheader('# of Crimes by Day of Month')
        st.write(
            pd.DataFrame(
                grp_data.groupby(['C_Day of month'],
                                 sort=False)['Count'].count().rename_axis(
                                     ["Day of Month"])))

    # Bar chart to show the Top 10 Crimes using plotly
    st.subheader(" Top 10 Crimes ")
    grp_data = crime_data.copy()
    grp_data['Count'] = 1
    k = pd.DataFrame(
        grp_data.groupby(['C_Descrip'],
                         sort=False)['C_Address'].count().rename_axis(
                             ["Type of Crime"]).nlargest(10))
    Crime = pd.Series(k.index[:])
    Count = list(k['C_Address'][:])
    Crime_Count = pd.DataFrame(list(zip(Crime, Count)),
                               columns=['Crime', 'Count'])
    fig = px.bar(Crime_Count,
                 x='Crime',
                 y='Count',
                 color='Count',
                 labels={
                     'Crime': 'Crime Type',
                     'Count': 'Crime Count'
                 })
    st.plotly_chart(fig)

    # Slider to select the required day of month to analyse
    st.subheader('Crime Location on Map - Select the day of a Month')
    Day_filter = st.slider('', 1, 31, 5)
    Crime_Filter = crime_data[crime_data['C_Day of month'] == Day_filter]

    # Map to show the physical locations of Crime for the selected day.
    midpoint = (np.average(Crime_Filter["lat"]),
                np.average(Crime_Filter["lon"]))

    st.deck_gl_chart(
        viewport={
            "latitude": midpoint[0],
            "longitude": midpoint[1],
            "zoom": 11,
            "pitch": 40,
        },
        layers=[{
            "type": "HexagonLayer",
            "data": Crime_Filter,
            "radius": 80,
            "elevationScale": 4,
            "elevationRange": [0, 1000],
            "pickable": True,
            "extruded": True,
        }],
    )

    # Histogram to show the no of Crimes by Hour for the selcted day of month.
    hist_values = np.histogram(Crime_Filter['C_Hour'], bins=24,
                               range=(0, 23))[0]
    st.bar_chart(hist_values)
    st.write(
        '--------------------------------- No. of Crimes by Hour in a given day ---------------------------------'
    )
    st.success("     ")

    if st.checkbox('Like Balloons?'):
        st.balloons()
Exemple #20
0
if len(options) > 0:
    data = data[data['gevi'].isin(options)]

#%%
############# Plotting - map
midpoint = (np.average(df["lat"]), np.average(df["lon"]))
st.deck_gl_chart(
    viewport={
        #        "mapStyle": "mapbox://styles/mapbox/light-v9",
        #        "mapboxApiAccessToken": '<pk.eyJ1IjoibGFyc2tpbGxhYXJzIiwiYSI6ImNrMWc2aHVmeDAwN2ozb3Fva2prM3cybjQifQ.G0kykI805dHb9fBDxkPy2Q>',
        "latitude": midpoint[0],
        "longitude": midpoint[1],
        "zoom": 6.2,
        "pitch": 0,
    },
    layers=[{
        "type": "HexagonLayer",
        "data": data,
        "radius": 2500,
        "elevationScale": 4,
        "elevationRange": [0, 1000],
        "pickable": True,
        "extruded": True,
    }],
)

#%%
#############%% Plotting - linechart
## Kies uit uren of dagen
#groupmode = st.sidebar.radio('Kies uren of dagen',('Uren','Dagen'))
#
Exemple #21
0
                    "pickable": True,
                    "extruded": True
                }
            }
        count = count + 1
    return BUS_LAYERS


csv_data = from_data_file(csv_filename)
first = csv_data.values[count]  #st.write()
cur_date = first[0]

ALL_DATA = getAllData(csv_data)
viewport = {"latitude": 49.203, "longitude": -2.130, "zoom": 11, "pitch": 30}
iterator_text = st.empty()
chart = st.deck_gl_chart(viewport=viewport)

while True:
    for item in ALL_DATES:
        selected_layers = [
            layer for layer_name, layer in ALL_DATA["Bus"][item].items()
        ]
        chart.deck_gl_chart(viewport=viewport, layers=selected_layers)
        iterator_text.text(item)
        time.sleep(1)

#def splitdate(date):
#    split = date.split('-')
#    split_years = split[0]
#    split_months = split[1]
#    split_days = split[2]
st.header('Bokeh Charts')
st.bokeh_chart(p)

df = pd.DataFrame(np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
                  columns=['lat', 'lon'])

st.header('')
st.deck_gl_chart(viewport={
    'latitude': 37.76,
    'longitude': -122.4,
    'zoom': 11,
    'pitch': 50,
},
                 layers=[{
                     'type': 'HexagonLayer',
                     'data': df,
                     'radius': 200,
                     'elevationScale': 4,
                     'elevationRange': [0, 1000],
                     'pickable': True,
                     'extruded': True,
                 }, {
                     'type': 'ScatterplotLayer',
                     'data': df,
                 }])

# Create a graphlib graph object
st.header('Graphviz Chart')

st.graphviz_chart('''
    digraph {
        run -> intr
Exemple #23
0
    def test_use_container_width_true(self):
        """Test that it can be called with no args."""
        st.deck_gl_chart(use_container_width=True)

        c = self.get_delta_from_queue().new_element.deck_gl_chart
        self.assertEqual(c.use_container_width, True)
    gpx['device'] = secrets.token_hex(nbytes=16)
    gpx['colorR'] = random.randint(0,255)
    gpx['colorG'] = random.randint(0,255)
    gpx['colorB'] = random.randint(0,255)
    gpx.index = gpx.index.map(lambda x: x.replace(year=2020, month=3, hour=12, day=20))
    gs.append(gpx) 

gs = pd.concat(gs) 
st.write("Data gathered by multiple gnss enabled devices")
st.write(gs[['latitude', 'longitude', 'altitude', 'device']]) 
g0 = gs
midpoint=(np.average(g0['latitude']), np.average(g0['longitude'])) 

st.write('Location tracks of possible contamination, different color per device') 

st.deck_gl_chart(
        viewport={ 
            'latitude': midpoint[0], 
            'longitude':  midpoint[1], 
            'zoom': 18,
            #'pitch': 50,
            }, 
        layers=[{ 
            'type': 'ScatterplotLayer',
            'data': gs, 
            'radiusScale': 0.01, 
            'radiusMinPixels': 1, 
            #'getFillColor': [248, 24, 148], 
            }]
        )
def main():
    """Car Evaluation with ML Streamlit App"""

    st.title(
        "Turbine energy prediction using weather conditions(click '>' to know prediction)"
    )
    st.subheader(" ML App")
    #st.image(load_image("car_images/car.jpg"),width=300, caption='Images')

    activities = ['EDA', 'Prediction', 'About']
    choices = st.sidebar.selectbox("Select Activity", activities)

    if choices == 'EDA':
        st.subheader("EDA")
        st.title('Our Dataset')
        st.dataframe(data2)

        def query_ip(ips):
            df2 = pd.DataFrame()
            for ip in ips.split(','):
                ip = ip.strip()
                response = requests.get(f'{API_URL}{ip}?api-key={API_KEY}')
                if response.status_code == 200:
                    data = json.loads(response.content)
                    df2 = df2.append(pd.DataFrame(pd.json_normalize(data)))

            return df2

        st.title('IP Geolocation')
        persons = st.text_input(
            'enter a 4-digit ip (ex-8.8.8.8:United states etc) of country to show your country details you can enter multiple ip separated by comma'
        )
        ips = st.text_area(
            'IP addresses of country separated by comma(EX-8.8.8.8,4.4.4.4)',
            persons)
        if st.button('Click to Get location'):
            df1 = query_ip(ips)
            st.dataframe(df1)
            st.table(df1[[
                'ip', 'emoji_flag', 'country_name', 'city', 'asn.name',
                'asn.type'
            ]].reset_index())
            st.deck_gl_chart(layers=[{
                'data': df1,
                'type': 'TextLayer',
                'getText': 'ip',
            }, {
                'data': df1,
                'type': 'ScatterplotLayer',
                'getRadius': 1e2,
            }])

        st.title('Overview of dataset')
        data = load_data('testingf.csv')
        data = data.drop(data.index[0])
        st.dataframe(data.head(5))

        data4 = data.drop(data.index[:-4])
        if st.checkbox("Show Summary of Dataset"):
            st.write(data.describe())

    # Show Plots
        if st.checkbox("Simple Value Plots "):
            st.write(data4['DE_wind_generation_actual'].value_counts().plot(
                kind='bar'))
            st.pyplot()

        if st.checkbox("Select Columns To Show"):
            all_columns = data.columns.tolist()
            selected_columns = st.multiselect('Select', all_columns)
            new_df = data[selected_columns]
            st.dataframe(new_df)

        if st.checkbox("Pie Plot"):
            st.write(
                data4['DE_wind_generation_actual'].value_counts().plot.pie(
                    autopct="%1.1f%%"))
            st.pyplot()

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

        b = st.selectbox('velocity at height 2m', tuple(v1h1_label))
        c = st.selectbox('velocity at height 10m', tuple(v2h2_label))
        d = st.selectbox('velocity at height 50m', tuple(v50m_label))
        e = st.selectbox("roughness length", tuple(z0_label))
        f = st.selectbox('atmosphere horizontal radiation', tuple(swtdn_label))
        g = st.selectbox("ground horizontal radiation ", tuple(swgdn_label))
        h = st.selectbox("temperature", tuple(t_label))

        pretty_data = {
            "velocity(2m)": b,
            "velocity(10m)": c,
            "velocity(50m)": d,
            "roughness length": e,
            "atmosphere horizontal radiation": f,
            "ground horizontal radiation": g,
            "temperature": h
        }
        st.subheader("Options Selected")
        st.json(pretty_data)

        st.subheader("weather data selected as for wind energy prediction")
        # Data To Be Used
        sample_data1 = [b, c, d, e]
        st.write(sample_data1)
        st.subheader("weather data selected as for solar energy prediction")
        sample_data2 = [f, g, h]
        st.write(sample_data2)
        prep_data1 = np.array(sample_data1, dtype='float64').reshape(1, -1)
        prep_data2 = np.array(sample_data2, dtype='float64').reshape(1, -1)
        model_choice = st.selectbox(
            "Model Type(prediction for wind energy OR solar energy)",
            ['wind energy prediction', 'solar energy prediction'])
        if st.button('Evaluate'):
            if model_choice == 'wind energy prediction':
                predictor = load_prediction_models("logittony_w_model.pkl")
                prediction = predictor.predict(prep_data1)
                st.write(prediction)
                st.write(
                    "the wind energy prediction based on weather condition is")

            if model_choice == 'solar energy prediction':
                predictor = load_prediction_models("logitstark_w_model.pkl")
                prediction = predictor.predict(prep_data2)
                st.write(prediction)
                st.write(
                    "the solar energy prediction based on weather condition is"
                )

            if model_choice == 'MLP classifier':
                predictor = load_prediction_models("nn_clf_car_model.pkl")
                prediction = predictor.predict(prep_data)
                st.write(prediction)

            st.success(prediction)
    if choices == 'About':
        st.subheader("About")
        st.write(
            "This web app gives the prediction on energy capacity on based on weather condition"
        )
Exemple #26
0
import pandas as pd

np.random.seed(12345)

data = np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4]
df = pd.DataFrame(data, columns=['lat', 'lon'])

# Test syntax sugar for scatterplot basic charts:
#   st.deck_gl_chart(df).
viewport = {
    'latitude': 37.76,
    'longitude': -122.4,
    'zoom': 11,
    'pitch': 50,
}
st.deck_gl_chart(df, viewport=viewport)

# Test a similar chart but with a full dict spec:
#   st.deck_gl_chart(spec=spec_dict)
spec = {
    'viewport': {
        'latitude': 37.76,
        'longitude': -122.4,
        'zoom': 11,
        'pitch': 50,
    },
    'layers': [{
        'data': df,
        'type': 'ScatterplotLayer',
        'radius': 250,
        'extruded': True,
image_legend = Image.open('legend2.png')
st.image(image_legend, use_column_width=True)

st.deck_gl_chart(
            viewport={'mapStyle': "mapbox://styles/mapbox/dark-v10",
                'latitude': map_graph['lat'].median(),
                'longitude':  map_graph['lon'].median(),
                'zoom': 2.6},
            layers=[{
                'type': 'ScatterplotLayer',
                'data': map_graph,
                'legend': True,
                'radiusScale': 20,
                'getLatitude': ['lat'],
                'getLongitude': ['lon'],
                'radiusMinPixels': 5,
                'getFillColor': [250, 20, 160],
                'pickable': True,
                'auto_highlight': True},
                {'type': 'ScatterplotLayer',
                'data': db_graph,
                'getLatitude': ['lat'],
                'getLongitude': ['lon'],
                'radiusScale': 20,
                'radiusMinPixels': 4,
                'getFillColor': [65, 105, 225, 180],
                'pickable': True,
                'auto_highlight': True}])
    

data = pd.read_csv('cleaned_df.csv')
#     pd.read_csv('dist_mat.csv')

st.title('Locatie stations en Afritten van rijkswegen')

radius = st.slider('Straal vanaf station', min_value=50, max_value=10000)
st.deck_gl_chart(viewport={
    'latitude': station_selected['lat'].tolist()[0],
    'longitude': station_selected['lon'].tolist()[0],
    'zoom': 12,
    'pitch': 50,
},
                 layers=[
                     {
                         'id': 'radius1',
                         'data': station_selected,
                         'type': 'ScatterPlotLayer',
                         'getRadius': radius,
                         'getColor': [230, 230, 30, 127],
                     },
                     {
                         'id': 'divergents',
                         'data': snelwegen,
                         'type': 'ScatterPlotLayer',
                         'getRadius': 50,
                         'getColor': [75, 205, 250, 230]
                     },
                 ])

st.markdown('''
## Natural Hubs
Dit dashboard toont de afritten van alle rijkswegen in Nederland en de afstand
tot treinstations. De Radius is configureerbaar en laat zien welke afritten zich binnen deze straal bevinden.
        if city_result is None:
            url = 'http://api.map.baidu.com/geocoding/v3/?address={0}&city={2}&output=json&ak={1}'.format(
                city,
                'm7CLmkXFXEMEgOh1lMraLo8vnWagEhP3',
                area)
            # print(url)
            process = json.loads(requests.get(url).text)
            # print(process)
            if process['status'] == 0:
                cities.insert_one({'city': city, 'detail': process['result']})
                # print('web')
                city_location = process['result']['location']
            else:
                pass
        else:
            # print('local')
            city_location = city_result['detail']['location']
        # print(city_location)
        processed_data.append({
            'confirm': detail['confirm'],
            'lng': city_location['lng'],
            'lat': city_location['lat']})
df = pd.DataFrame(
    np.random.randn(1000, 2) / [114, 30],
    columns=['lat', 'lon'])
print(df)
st.deck_gl_chart(layers=[{
    'data': df,
    'type': 'ScatterplotLayer'
}])