Ejemplo n.º 1
0
def policy_map_button():
    data = pd.read_csv('StatePolicies.csv')
    m = folium.Map(tiles="Stamen Watercolor",
                   zoom_start=3,
                   max_zoom=6,
                   min_zoom=2,
                   zoom_Animation=False)
    states = json.load(open('india_states.geojson', 'r'))
    style1 = {'fillOpacity': '0', 'color': 'black', 'weight': '0.8'}
    layer = folium.GeoJson(states,
                           name='geojson',
                           style_function=lambda x: style1).add_to(m)
    m.fit_bounds([[26.051054453379013, 64.6016217019466],
                  [27.51097571534207, 100.03322049016737]])
    for i in range(0, len(data)):
        htmlFile = data.iloc[i]['FileName']
        html = open(htmlFile, 'r')
        #st.write(html)
        html = html.read()
        #html = """"""
        iframe = branca.element.IFrame(html=html, width=400, height=300)
        popup = folium.Popup(iframe, parse_html=True)
        print(data.iloc[i]['Latitude'])
        marker = folium.Marker(
            [data.iloc[i]['Latitude'], data.iloc[i]['Longitude']],
            popup=popup,
            icon=folium.Icon(color='green', icon='info-sign')).add_to(m)
    folium_static(m)
def main():


    with open("style.css") as f:
        st.markdown('<style>{}</style>'.format(f.read()), unsafe_allow_html=True)

    st.title("Automated Wild Fire Detection App")

    uploaded_image = Image.open('test_images/image2.png')
    st.markdown("** Fire Observation: **")
    st.image(uploaded_image, width = 500)
    
    accept_user_data()
    
    #### Show the Satellite
    st.markdown("** The Latest Fire Location from Our Satellite **: ")
    token = "pk.eyJ1IjoiZTk2MDMxNDEzIiwiYSI6ImNqdDcxbW1kMzBhbWE0M25uYmswaWNnc3EifQ.xUELGj4ak4EIaPPYQUnYug" # your mapbox token
    tileurl = 'https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}@2x.png?access_token=' + str(token)
    # center
    m = folium.Map(location=[22.999727, 121.127028], zoom_start=2, tiles=tileurl, attr='Mapbox')
    
    # add marker for Fire Location
    satellitePlot = showMap()
    maps = satellitePlot[['latitude','longitude']]
    locations = maps[['latitude', 'longitude']]
    locationlist = locations.values.tolist()
    for point in range(1, 101):
        folium.Marker(locationlist[-point], icon=folium.Icon(color='orange', icon_color='red', icon='fire',radius=4, angle=0)).add_to(m)
    folium_static(m)
    
    plotData = showMap()
    st.subheader("Fire Visualization for the past 48 hours:")
    st.map(plotData, zoom = 0)
Ejemplo n.º 3
0
def displayMap(map, decision):
    blur = st.checkbox("Blur")
    large = st.checkbox("Large Points")
    add = 0
    if large:
        add = 6
    if blur:
        b = 15
        rad = 20 + add
    else:
        b = 1
        rad = 4 + add
    if(decision == 'avg'):
        minMap = map[['TAVG', 'latitude', 'longitude', 'station', 'state']].groupby(['station', 'latitude','longitude', 'state']).min().reset_index()
        maxMap = map[['TAVG', 'latitude', 'longitude', 'station', 'state']].groupby(['station', 'latitude','longitude', 'state']).max().reset_index()
        map = map[['TAVG', 'latitude', 'longitude', 'station', 'state']].groupby(['station', 'latitude','longitude', 'state']).mean().reset_index()
        map['avg'] = maxMap['TAVG'] - minMap['TAVG']
    
    else:
        map = map[[decision, 'latitude', 'longitude', 'station', 'state']].groupby(['station', 'latitude','longitude', 'state']).mean().reset_index()

    max_amount = float(map[decision].max())
    hmap = folium.Map(location=[40, -100], zoom_start=4)

    hm_wide = HeatMap(list(zip(map['latitude'].values, map['longitude'].values, map[decision].values)),
        min_opacity=0, max_val=max_amount, radius=rad, blur=b, max_zoom=5, control_scale = True)

    hmap.add_child(hm_wide)
    folium_static(hmap)
    graph = st.checkbox('Show Graph')
    if graph:
        showGraph(map, decision)
Ejemplo n.º 4
0
def port_folio_density(data):
    # Houses density
    st.title("Region Overview")
    st.write(
        "The map 'Houses Density' show the houses density distributions and some its features like 'price', 'area', year of built ... "
    )

    c1, c2 = st.beta_columns((1, 1))
    c1.header("Houses Density")

    density_map = folium.Map(
        location=[data['lat'].mean(), data['long'].mean()],
        default_zoom_start=15)

    sam = data.sample(1000)

    cluster = MarkerCluster().add_to(density_map)
    for name, row in sam.iterrows():
        folium.Marker(
            [row['lat'], row['long']],
            popup=
            'Sold S$ on: {1}. Features: {2} sqft, {3} bedrooms, {4} bathrooms, year built: {5}'
            .format(row['price'], row['date'], row['sqft_living'],
                    row['bedrooms'], row['bathrooms'],
                    row['yr_built'])).add_to(cluster)

    with c1:
        folium_static(density_map)

    return None
Ejemplo n.º 5
0
def map_display(data):
    '''create and fill the maps with the filtered dataset infos.'''
    st.markdown('## :earth_americas: **Rental Houses Map**')
    c1, c2 = st.beta_columns((1, 1))

    # 1st map - houses for rent
    lat = 51.1642292
    long = 10.4541194

    map_b = folium.Map(location=[lat, long], zoom_start=5.5)

    prices = plugins.MarkerCluster().add_to(map_b)

    for lat, lng, i in zip(data['lat'],
                           data['long'],
                           list(range(data.shape[0]))):
        label = f'{data["street"].values[i]} - Price: €{data["montly_rent"].values[i]} - {data["pets"].values[i]}'
        label = folium.Popup(label, parse_html=True)
        folium.Marker(
            location=[lat, lng],
            icon=None,
            popup=label).add_to(prices)

    folium.GeoJson(geo_json_data, style_function=lambda feature: {'color': 'darkred', 'weight': 0.5, }).add_to(map_b)

    folium_static(map_b, width=1200, height=550)

    return None
Ejemplo n.º 6
0
def location_map(lat, long):
    m = folium.Map(location=[lat, long], zoom_start=10)

    # add marker for Liberty Bell
    tooltip = "House"
    folium.Marker([lat, long], popup="Housing", tooltip=tooltip).add_to(m)

    # call to render Folium map in Streamlit
    folium_static(m)
Ejemplo n.º 7
0
def portfolio_density(data, geofile):
    # ==================
    # Densidade de Portfólio
    # ==================

    st.title('Region Overview')

    c1, c2 = st.beta_columns((1, 1))
    c1.header('Portfolio Density')

    df = data.sample(1000)

    # Base Map - Folium

    density_map = folium.Map(
        location=[data['lat'].mean(), data['long'].mean()],
        default_zoom_start=15)

    marker_cluster = MarkerCluster().add_to(density_map)
    for name, row in df.iterrows():
        folium.Marker(
            [row['lat'], row['long']],
            popup=
            'Sold R${0} on: {1}. Features: {2} sqft, {3} bedrooms, {4} bathrooms, year built: {5}'
            .format(row['price'], row['date'], row['sqft_living'],
                    row['bedrooms'], row['bathrooms'],
                    row['yr_built'])).add_to(marker_cluster)

    with c1:
        folium_static(density_map)

    # Region Price Map

    c2.header('Price Density')

    df = data[['price', 'zipcode']].groupby('zipcode').mean().reset_index()

    df.columns = ['ZIP', 'PRICE']

    # df = df.sample(10)

    geofile = geofile[geofile['ZIP'].isin(df['ZIP'].tolist())]

    region_price_map = folium.Map(
        location=[data['lat'].mean(), data['long'].mean()],
        default_zoom_start=15)
    region_price_map.choropleth(data=df,
                                geo_data=geofile,
                                columns=['ZIP', 'PRICE'],
                                key_on='feature.properties.ZIP',
                                fill_color='YlOrRd',
                                fill_opacity=0.7,
                                line_opacity=0.2,
                                legend_name='Avg. Price')
    with c2:
        folium_static(region_price_map)
    return None
def portfolio_density(data, geofile):
  # ------------------------
  # 1.5- Um mapa com a densidade de portfólio por região e também densidade de preço
  # ------------------------

  #  Densidade de Portfolio
  # ------------------------
  st.title('Overview por Região')

  c1, c2 = st.beta_columns((1, 1))
  c1.header('Densidade de Portfolio')

  df = data.sample(10)

  # Base Map - Folium
  densidade_map = fol.Map(location=[data['latitude'].mean(),
                                   data['longitude'].mean()],
                         default_zoom_start=15)
  marker_cluster = MarkerCluster().add_to(densidade_map)
  for name, row in df.iterrows():
      fol.Marker( [row['latitude'], row['longitude']],
                 popup='Sold R${0} on: {1}. Features: {2} sqft, {3} bedrooms, {4} bathrooms, year built: {5}'.format(row['price'],
                                                                                                                      row['date'],
                                                                                                                     row['sqft_living'],
                                                                                                                     row['bedrooms'],
                                                                                                                     row['bathrooms'],
                                                                                                                     row['yr_built'])).add_to(marker_cluster)
  with c1:
      folium_static(densidade_map)

  #  Densidade de Preço
  # ------------------------
  # Mapa de preço por região
  c2.header('Densidade de Preço')

  df = data[['price', 'zipcode']].groupby('zipcode').mean().reset_index()
  df.columns = ['zip', 'price']
  # df = df.sample(10)

  regiao_map = fol.Map(location=[data['latitude'].mean(),
                                   data['longitude'].mean()],
                         default_zoom_start=15)


  geofile = geofile[geofile['ZIP'].isin( df['zip'].tolist() )]

  regiao_map.choropleth(data=df, geo_data=geofile, columns=['zip', 'price'], key_on='feature.properties.ZIP',
                        fill_color='YlOrRd',
                        fill_opacity=0.7,
                        line_opacity=0.2,
                        legend_name='MEDIA PREÇO')
  with c2:
      folium_static(regiao_map)

  
  return None
Ejemplo n.º 9
0
def app():
    # st.set_page_config(layout="wide")

    st.title('NYC Covid Map by Zipcode')

    folium_static(m)

    st.write(
        'This is a map of the five borough that make up New York City. We see many covid looking icons scattered all across the map. Each one of these icons represent an individual zipcode in New York City. If you zoom in and click on a covid icon, you will see a pop up that inform sus whhich zipcode it is, the name of the neighborhood, the current cases and the positivity rate within the past 7 days.'
    )
Ejemplo n.º 10
0
def getMap(coordinates):  ### touples array! [(float, float), (float, float)]
    if not coordinates:  ## if no coordinates, show general map
        return folium_static(f.Map())

    mapIt = f.Map()
    for coord in coordinates:
        mapIt = f.Map(location=[coord[0], coord[1]], zoom_start=4)
        f.Marker([coord[0], coord[1]]).add_to(mapIt)

    return folium_static(mapIt)
def main():

    st.title('Smart Traffic System :sunglasses:')
    input_date = st.date_input('Pick a date', value = datetime.datetime(2019, 1, 1),\
                               min_value = datetime.datetime(2019, 1, 1), \
                               max_value = datetime.datetime(2020, 1, 1))
    input_time = st.time_input('Pick a time', value=datetime.time(0, 0))
    Manhattan_geo = get_geo()
    Manhattan_map = get_map(Manhattan_geo, input_date, input_time)
    #     Manhattan_map.save('map.html')
    folium_static(Manhattan_map)
Ejemplo n.º 12
0
def get_school_district_map(school_district_choice, latitude, longitude, graduation_rate_real):
    map = folium.Map([latitude, longitude], tiles="OpenStreetMap", zoom_start=13)
    folium.Marker(
        location=[latitude, longitude],
        tooltip=f"""
        In {school_district_choice.title()}<br>
        The real-world graduation rate is {round(graduation_rate_real * 100)}%
        """,
        draggable=True,
        icon=folium.Icon(icon="cloud")).add_to(map)
    folium_static(map)
    return None
def displayMap(map):

    st.write("Airbnb Listing density Heat Map")
    hmap = folium.Map(location=[34, -118.5], zoom_start=9)

    hm_wide = HeatMap(map[['latitude', 'longitude']],
                      radius=5,
                      min_opacity=0,
                      blur=1,
                      control_scale=True)

    hmap.add_child(hm_wide)
    folium_static(hmap)
Ejemplo n.º 14
0
def make_map(arr):
    if len(arr) > 0:
        mapD = folium.Map(location=[19.076090, 72.877426], zoom_start=10)
        geolocator = Nominatim(user_agent="http")
        for item in arr:
            i = json.loads(item.replace('\'', '\"'))
            coord = i['coordinates']
            str_coord = "" + str(coord[0]) + ", " + str(coord[1])
            location = geolocator.reverse(str_coord)
            folium.Marker(coord, popup=location).add_to(mapD)
        folium_static(mapD)
    else:
        st.text('No Geo data available')
Ejemplo n.º 15
0
    def render(self):
        self._add_point()
        folium_static(self.map, 1750, 500)

        # Some custom CSS have all buttons the same width
        st.markdown("<style>.stButton>button {width: 7.6em;} </style>",
                    unsafe_allow_html=True)

        if st.button("Apply Changes To The Mission!"):
            me = MissionEditor("backend\\temp.miz")
            me.edit_waypoints(self.waypoints)
            st.balloons()
            href = self._get_binary_file_downloader_html(
                'temp.miz', file_label=self.selected_mission)
            st.markdown(href, unsafe_allow_html=True)
Ejemplo n.º 16
0
def plot_map(df_store, df_tb, IDs, sizes, colorvalues, init_lat, init_lon,
             selected_ID, mapcolor, mapsize):

    from streamlit_folium import folium_static
    import folium

    mapper = map_color(
        source_range=colorvalues,  #df_tb[colors].values,
        nun_colors=df_store['store_id'].size,
        map_color_name='viridis')

    m = folium.Map(width=500,
                   height=500,
                   location=[init_lat, init_lon],
                   tiles="OpenStreetMap",
                   zoom_start=13)

    for store_id in IDs:

        posto = df_store.loc[df_store['store_id'] == store_id]

        color_value = colorvalues[np.where(
            IDs ==
            store_id)[0][0]]  #posto_demais_informacoes[colors].values[0]
        radius = mapsize[np.where(IDs == store_id)[0][0]]

        lat = posto['latitude'].values[0]
        lon = posto['longitude'].values[0]

        folium.CircleMarker(
            [lat, lon],
            radius=radius,
            fill_opacity=0.7,
            tooltip=str(np.where(IDs == store_id)[0][0]),
            popup=
            "<p>Please select the new store using the sidebar</p>",  #str(lon),
            color=mapcolor[str(color_value)],  #"black",
            fill=True,
            fill_color=mapcolor[str(
                color_value)],  #calc_color(mapper, color_value)#"green",   
        ).add_to(m)
        folium.Marker([init_lat, init_lon],
                      popup="<p>Selected Store <b> Real ID: " +
                      str(selected_ID) + " <b>ID: " +
                      str(np.where(IDs == store_id)[0][0]) + "</p>",
                      tooltip="Selected Store").add_to(m)
    folium_static(m)
    m.save('LA collisions.html')
Ejemplo n.º 17
0
def write():
    st.title("Find a Person")
    data = load_data()
    village_names = list(data.Village.value_counts().index)
    village_names.sort()
    village_names.insert(0, "All villages")
    village = st.selectbox("Select village", village_names)

    if village != village_names[0]:
        data = data[data["Village"] == village]

    if village != village_names[0]:
        data = data[data["Village"] == village]

    st.header("Locate person by name in: " + village)
    name_list = list(set(data["Patron"].value_counts().index))
    name_list.sort()
    name = st.selectbox("Names", name_list)

    data = data[data["Patron"] == name]

    m = folium.Map(
        location=[data["latitude"].mean(), data["longitude"].mean()],
        zoom_start=10)

    for i in range(0, len(data)):
        name = data.iloc[i]["Patron"]
        address = data.iloc[i]["Address"]
        village = data.iloc[i]["Village"]
        directions = "https://www.google.com/maps/dir//" + str(
            data.iloc[i]["latitude"]) + "," + str(data.iloc[i]["longitude"])
        photo = "https://raw.githubusercontent.com/prabodhw96/Rohit/master/" + data.iloc[
            i]["Photo"]

        find_html = folium.Html(f"""<p style="text-align: center;">{name}</p>
									<p style="text-align: center;">{address}</p>
									<p style="text-align: center;">{village}</p>
									<p style="text-align: center;"><img src={photo} width="180" height="210" frameborder="0"></img>
									<p style="text-align: center;"><a href={directions} target="_blank" title="Directions to {name}"><b>Directions to {name}</b></a></p>
								""",
                                script=True)
        popup = folium.Popup(find_html, max_width=220)
        folium.Marker([data.iloc[i]["latitude"], data.iloc[i]["longitude"]],
                      popup=popup).add_to(m)
    folium_static(m)

    if st.checkbox("Show Raw Data", False):
        st.write(data)
Ejemplo n.º 18
0
def portfolio_density(data, geofile):
    st.title("Region Overview")
    c1, c2 = st.beta_columns((1, 1))
    c1.header("Portfolio Density")

    df = data.sample(10)
    # Base Map - Folium
    density_map = folium.Map(location=[data.lat.mean(),
                                       data.long.mean()],
                             default_zoom_start=15)

    marker_cluster = MarkerCluster().add_to(density_map)
    for name, row in df.iterrows():
        folium.Marker(
            [row["lat"], row["long"]],
            popup=
            f"Sold R$ {row.price} on: {row.date}. Features: {row.sqft_living} sqft, {row.bedrooms} bedrooms, {row.bathrooms} bathrooms, year built: {row.yr_built}",
        ).add_to(marker_cluster)

    with c1:
        folium_static(density_map)

    # Region Price Map
    c2.header("Price Density")
    df = data[["price", "zipcode"]].groupby("zipcode").mean().reset_index()
    df.columns = ["ZIP", "PRICE"]

    df = df.sample(10)
    geofile = geofile[geofile["ZIP"].isin(df["ZIP"].tolist())]
    region_price_map = folium.Map(location=[data.lat.mean(),
                                            data.long.mean()],
                                  default_zoom_start=15)

    folium.Choropleth(
        data=df,
        geo_data=geofile,
        columns=["ZIP", "PRICE"],
        key_on="feature.properties.ZIP",
        fill_color="Spectral",
        fill_opacity=0.7,
        line_opacity=0.2,
        legend_name="AVG PRICE",
    ).add_to(region_price_map)

    with c2:
        folium_static(region_price_map)

    return None
Ejemplo n.º 19
0
def content():

    st.title('What are the best locations for police stations? 👮🏻‍♂️')

    st.header('Clustering Analysis')

    df = get_data()
    df = df.dropna(subset=['Lat', 'Long'])
    df = df[df['Lat'] > 0]
    df_cluster = df.dropna()[['Lat', 'Long']]

    clust_labels, cent = doKmeans(df_cluster, 100)
    kmeans = pd.DataFrame(clust_labels)
    df_cluster.insert((df_cluster.shape[1]), 'kmeans', kmeans)
    arr = pd.DataFrame(data=cent, columns=['latitude', 'longitude'])

    # create a map
    this_map = folium.Map(width=1500,
                          height=500,
                          location=[42.361145, -71.057083])

    def plotDot(point):
        '''input: series that contains a numeric named latitude and a numeric named longitude
        this function creates a CircleMarker and adds it to your this_map'''
        folium.Marker(
            location=[point.latitude, point.longitude],
            radius=2,
            weight=5,
            icon=DivIcon(
                html=
                '<img alt="Police Icon of Colored Outline style - Available in SVG, PNG, EPS, AI &amp; Icon  fonts" class="n3VNCb" src="https://cdn.iconscout.com/icon/premium/png-256-thumb/police-1623568-1375513.png" data-noaft="1" jsname="HiaYvf" jsaction="load:XAeZkd;" style="width: 35px; height: 35px; margin: 0px;">',
                icon_size=(1, 1),
                icon_anchor=(0, 0),
            )).add_to(this_map)

    # use df.apply(,axis=1) to "iterate" through every row in your dataframe
    arr.apply(plotDot, axis=1)

    # Set the zoom to the maximum possible
    this_map.fit_bounds(this_map.get_bounds())

    # Save the map to an HTML file
    folium_static(this_map)

    st.markdown(
        'On this map, latitude and longitude points\'re clustered into 100 points, then visualized the center points of these clusters to see best locations for police stations. '
        '\n\n\n Please note that the number of cluster depends on police force of Boston Police Department. It can be increase or decrease according to it.'
    )
Ejemplo n.º 20
0
def load_map(data):
    data_map = geopandas.read_file(geofile)
    mapa = folium.Map(location=[data['lat'].mean(), data['long'].mean()])

    marker_cluster = MarkerCluster().add_to(mapa)
    for name, row in data.iterrows():
        folium.Marker(location=[row['lat'], row['long']],
                      popup=f'''
        ID:{row["id"]}
        PREÇO:{row["price"]}
        BEIRA-MAR:{row["waterfront"]}
        BANHEIROS:{row["bathrooms"]}
        QUARTOS:{row["bedrooms"]}
        ''').add_to(marker_cluster)

    df = data[['price', 'zipcode']].groupby('zipcode').mean().reset_index()
    data_map = data_map[data_map['ZIP'].isin(data['zipcode'].tolist())]
    folium.Choropleth(geo_data=data_map,
                      data=df,
                      columns=['zipcode', 'price'],
                      key_on='feature.properties.ZIP',
                      fill_color='YlOrRd',
                      fill_opacity=0.9,
                      line_opacity=0.4).add_to(mapa)
    return folium_static(mapa)
def show_map(df_fin):
    folium_map = folium.Map(location=[49.286310, -123.134108], zoom_start=12, height='65%')

    for index,row in df_fin.iterrows():
        popup = '<a href="' + row["listing_url"] + '"target="_blank"> Visit! </a>'
        folium.Marker([row["latitude"], row["longitude"]], popup=popup, tooltip=row["name"]).add_to(folium_map)

    return folium_static(folium_map)
Ejemplo n.º 22
0
def app(df_listings, df_attractions, df_predictions, facilities):
    st.subheader("Prediction of price for a new listing")
    st.markdown(
        "If you are interested in adding a new listing to Airbnb, this tool will help you to find an appropriate price "
        "for your house according to the demand for the specific neighbourhood and the facilities that you are offering. "
        "All you have to do is to add the neighbourhood of your choise and the amenities you are planning to provide.")

    X_test = pd.DataFrame(columns=df_predictions.columns)
    X_test.loc[len(X_test)] = 0

    neighs = df_listings['neighbourhood'].unique()
    rprt_status = st.sidebar.selectbox("Choose Neighbourhood(*)", neighs)
    container = st.sidebar.beta_container()
    all = st.sidebar.checkbox("Select all")

    if all:
        selected_options = container.multiselect("Select one or more amenities:",
                                                 facilities, facilities)
    else:
        selected_options = container.multiselect("Select one or more amenities:",
                                                 facilities)

    if st.button('Predict the price of your new listing'):
        geolocator = Nominatim(user_agent="electra")
        location = geolocator.geocode(rprt_status + ", New York")
        X_test.distance = haversine(df_attractions, location.latitude, location.longitude)
        X_test[selected_options] = 1
        X_test[rprt_status] = 1
        model = RandomForestRegressor(max_depth=8, min_samples_leaf=0.1, min_samples_split=0.1, n_estimators=50)
        model.fit(df_predictions, df_listings.price.to_numpy()[:, np.newaxis])
        y_pred = model.predict(X_test)

        map_hooray = folium.Map([location.latitude, location.longitude], zoom_start=11, tiles="OpenStreetMap")

        html = "<font color= \"#225d7a\" face = \"Raleway\" size = \"5\"><strong>Price: {}$</strong></font>".format(
            str(round(y_pred[0])))

        folium.Marker([location.latitude, location.longitude], icon=DivIcon(icon_size=(150, 10),
                                                                            icon_anchor=(60, 20), html=html)).add_to(
            map_hooray)
        map_hooray.add_child(folium.CircleMarker([location.latitude, location.longitude], radius=80,
                                                 color="#428DB2",
                                                 fill=True,
                                                 fill_color="#428DB2", ))

        folium_static(map_hooray, width=1000, height=600)
Ejemplo n.º 23
0
def main():
    st.beta_set_page_config(page_title="DWD Stations")

    st.write("# DWD stations near IMK-IFU/ KIT 🏔🌦")

    data_resolution = select_data_resolution()
    max_station_distance = select_max_station_distance()
    observation_years = select_observation_years()

    closest_stations = find_close_stations(
        dist=max_station_distance, res=data_resolution
    )
    filtered_stations = filter_by_dates(closest_stations, *observation_years)

    st.write(f"Number of stations: {len(filtered_stations)}")

    station_map = create_map(filtered_stations, tereno_stations, max_station_distance)
    folium_static(station_map)
Ejemplo n.º 24
0
def esda(sdf):
    # sdf = get_pol_db()
    sdf = sdf.fillna(0)
    sdf.estrato = sdf.estrato.astype(int)
    variables = [v[1] for v in cols_traduccion_geo.values()][3:-1]
    # variables = sdf.columns[3:-1]
    variables.insert(0,'Select')

    st.markdown("""
    ### Exploratory spatial data analysis: 
    The data showed is on neighborhood level this data is not exactly the complete data, but works to get a better visualization
    """)
    # st.title('El eda')
    var_name = st.selectbox("Select a variable (the map is the mean (continuous) and mode (categorical) of the variable of each neighborhoood)",variables)
    
    if var_name != 'Select':
        var = [k for k,v in cols_traduccion_geo.items() if v[1] == var_name][0]
        folium_static(neighborhoodmap(sdf,var,var_name))
Ejemplo n.º 25
0
Archivo: pag1.py Proyecto: Frenz86/NDFD
def show_maps_Flood():
    colors = [
        '#2b83ba', '#abdda4', '#ffffbf', '#fdae61', '#d7191c'
    ]  # these have been assigned to each FloodRisk category in the GeoJSON file on QGIS!!!
    m = folium.Map(location=[15.4275, -61.3408],
                   zoom_start=11)  # center of island overview

    # # Show Landslide GeoJSON to the map
    # folium.GeoJson(
    # landslide_json,
    # name='Landslide',
    # 	style_function=lambda feature: {
    # 	# 'fillColor': feature['properties']['Color'],
    # 	# 'color' : feature['properties']['Color'],
    # 	'weight' : 1,
    # 	'fillOpacity' : 0.3,
    # 	}
    # ).add_to(m)

    ## Show risk zones
    folium.GeoJson(flood_gj,
                   name='Flood Risk',
                   style_function=lambda feature: {
                       'fillColor': feature['properties']['Color'],
                       'color': feature['properties']['Color'],
                       'weight': 1,
                       'fillOpacity': 0.3,
                   }).add_to(m)

    # Setup colormap MUST USE SAME COLORS AS QGIS GEOJSON FILE!!!!
    levels = len(colors)
    cmap = branca.colormap.LinearColormap(colors, vmin=0,
                                          vmax=4).to_step(levels - 1)
    cmap.add_to(m)

    # Enable lat-long Popup; LayerControl; Call to render Folium map in Streamlit
    m.add_child(
        folium.ClickForMarker(popup='Waypoint (Double-click to remove it)')
    )  # and click-for-marker functionality (dynamic)
    m.add_child(
        folium.LatLngPopup()
    )  # It's not possible to save lat long automatically from clicking on it :-( . # https://github.com/python-visualization/folium/issues/520
    folium.LayerControl().add_to(m)
    folium_static(m)
Ejemplo n.º 26
0
def create_mainscreen(df, pr, APP_NAME):
    st.title(APP_NAME)

    # Folium mapping example: center on Sydney Opera House
    m = folium.Map(location=[-33.85719805, 151.21512338473752], zoom_start=15)

    # add marker for Opera House
    tooltip = "Sydney Opera House"
    folium.Marker([-33.85719805, 151.21512338473752],
                  popup="Sydney Opera House",
                  tooltip=tooltip).add_to(m)

    # call to render Folium map in Streamlit
    folium_static(m)

    # Dataframe / Profiling example
    st.write(df)
    st.header('Data Profile:')
    st_profile_report(pr)
Ejemplo n.º 27
0
def main():
    # About Text
    st.title("DSC 106 Final Project")
    st.subheader("Created by Team Beeg Data")
    st.subheader("Team Members: Tanveer Mittal and Arjun Sawhney")
    st.subheader("")

    # Button to render plots
    render = st.button("Render Plots")

    # Load in and cache data
    df = load_data("data/NYPD_Complaint_Data_Historic.csv")

    # Render Line Plot
    st.markdown("# Line Plot of NYPD Complaints Since 2006:")
    complaints = st.multiselect(
        "Select Complaint Types to plot or select none to aggregate all 3:",
        ["Felony", "Misdemeanor", "Violation"],
        key=1)
    if render:
        complaints = [c.upper() for c in complaints]
        st.plotly_chart(get_plot_1(df, complaints)["plot"])

    # Render Bar Chart
    st.markdown("# Bar Chart of Criminal Offenses:")
    if render:
        st.plotly_chart(get_plot_2(df)["plot"])

    # Render Heatmap
    st.markdown("# Proprtional Symbol Map of NYPD Complaints by Precinct:")
    year = st.slider("Select year to plot:", min_value=2006, max_value=2019)
    complaints_2 = st.multiselect(
        "Select Complaint Types to plot or select none to aggregate all 3:",
        ["Felony", "Misdemeanor", "Violation"],
        key=2)
    if render:
        complaints_2 = [c.upper() for c in complaints_2]
        folium_static(get_plot_3(df, year, complaints_2)["plot"])

    # Render Sankey Diagram
    st.markdown("# Sankey Diagram of Suspect and Victim Races:")
    if render:
        st.plotly_chart(get_plot_4(df)["plot"])
Ejemplo n.º 28
0
def show_maps(data, threshold_scale):
    maps = folium.Choropleth(geo_data=data_geo,
                             data=data_all,
                             columns=['District', dicts[data]],
                             key_on='feature.properties.name',
                             threshold_scale=threshold_scale,
                             fill_color='YlOrRd',
                             fill_opacity=0.7,
                             line_opacity=0.2,
                             legend_name=dicts[data],
                             highlight=True,
                             reset=True).add_to(map_sby)

    folium.LayerControl().add_to(map_sby)
    maps.geojson.add_child(
        folium.features.GeoJsonTooltip(fields=['name', data],
                                       aliases=['District: ', dicts[data]],
                                       labels=True))
    folium_static(map_sby)
Ejemplo n.º 29
0
def load_map():
    #TODO

    st.title("Civic Day of Hacking Asset Map")

    sidebar_options()

    st.header("This is our asset map")

    map_lat = "MAR_LATITUDE"
    map_long = "MAR_LONGITUDE"

    df = pd.read_csv("data/full_ballot_data.csv",
                     dtype={
                         map_lat: float,
                         map_long: float
                     })
    # st.dataframe(df)
    st.write("")
    st.write("")

    first_lat = df[map_lat].mean()
    first_long = df[map_long].mean()

    m = folium.Map(location=[first_lat, first_long], zoom_start=16)

    # now place a marker for each row in df
    df.apply(lambda row: mark_map(row, m, map_lat, map_long, df.columns),
             axis=1)

    metro_df = pd.read_csv("data/Metro_Stations_in_DC.csv",
                           dtype={
                               "Y": float,
                               "X": float
                           }).dropna()
    # now place a marker for each row in df
    st.write(metro_df)
    df.apply(lambda row: mark_map(row, m, "Y", "X", metro_df.columns), axis=1)

    # might be able to hard code it here

    folium_static(m)
Ejemplo n.º 30
0
def gerar_mapa(df, cor, opcao):
    # Quartis
    num_quantiles = 4

    radius_labels = [100, 200, 300, 400]
    df['radius'] = pd.qcut(df['media_de_dias_ate_sentenca'],
                           q=num_quantiles,
                           labels=radius_labels[-num_quantiles:])

    if (opcao == "Mapa"):
        # Divisão dos dados para visualização no mapa
        color_labels = ['green', 'yellow', 'orange', 'red']
        df['color'] = pd.qcut(df['media_de_dias_ate_sentenca'],
                              q=num_quantiles,
                              labels=color_labels[:num_quantiles])

        if (cor != " - "):
            df = df[df['color'] == cor]

    if (opcao == "Comparação"):
        df['color'] = df['media_de_dias_ate_sentenca'].apply(
            definir_cores, media=int(media_nacional))

    # Bubble map do tempo médio até sentença para as varas constituintes
    m = folium.Map([-13.923403897723334, -49.92187499999999], zoom_start=4)

    for i in range(0, len(df)):
        folium.Circle(
            location=[df.iloc[i]['LAT'], df.iloc[i]['LONG']],
            popup=folium.Popup(u'Tempo: ' +
                               str(df.iloc[i]['media_de_dias_ate_sentenca']) +
                               ' dias',
                               parse_html=True,
                               max_width='100'),
            tooltip=df.iloc[i]['dadosBasicos.orgaoJulgador.nomeOrgao'],
            radius=int(df.iloc[i]['radius']),
            color=df.iloc[i]['color'],
            fill=True,
            fill_color=df.iloc[i]['color']).add_to(m)

    folium_static(m)
    return df