Ejemplo n.º 1
0
    def __init__(self, positions, colors, colormap=None, nb_steps=12,
                 weight=None, opacity=None, **kwargs):
        super(ColorLine, self).__init__(**kwargs)
        self._name = 'ColorLine'

        if colormap is None:
            cm = LinearColormap(['green', 'yellow', 'red'],
                                vmin=min(colors),
                                vmax=max(colors),
                                ).to_step(nb_steps)
        elif isinstance(colormap, LinearColormap):
            cm = colormap.to_step(nb_steps)
        elif isinstance(colormap, list) or isinstance(colormap, tuple):
            cm = LinearColormap(colormap,
                                vmin=min(colors),
                                vmax=max(colors),
                                ).to_step(nb_steps)
        else:
            cm = colormap
        out = {}
        for (lat1, lng1), (lat2, lng2), color in zip(positions[:-1], positions[1:], colors):  # noqa
            out.setdefault(cm(color), []).append([[lat1, lng1], [lat2, lng2]])
        for key, val in out.items():
            self.add_child(MultiPolyLine(val, color=key,
                                         weight=weight, opacity=opacity))
Ejemplo n.º 2
0
    def get_color_scale(options, vmin=0, vmax=1):
        ''' Gets a color array as given by options or builds a linear scale '''
        # Check if color list is given, escaping if true
        color_array = ViewConfReader.get_attribute_from_chart_spec(options, 'colorArray')
        if color_array:
            return color_array

        scale_def = ViewConfReader.get_attribute_from_chart_spec(
            options,
            'colorScale',
            {'name': 'Blues'}
        )

        plt = brewer2mpl.get_map(
            scale_def.get("name"),
            scale_def.get('nature', 'sequential'),
            scale_def.get("levels", 5),
            reverse=scale_def.get("order", "asc") == 'desc'
        )

        if "levels" in scale_def:
            scale = LinearColormap(
                plt.mpl_colors,
                vmin=0,
                vmax=int(scale_def.get("levels")) - 1
            )
            return [scale(i) for i in range(scale_def.get("levels"))]

        return LinearColormap(
            plt.mpl_colors,
            vmin=vmin,
            vmax=vmax
        )
Ejemplo n.º 3
0
def plot_linestring(geometry, speed_color=None, config=None):
    if (type(geometry) == LineString):
        geometry = gpd.GeoSeries(geometry)
    # set initial coords as first point of first linestring
    geometry_ = geometry.geometry[0]
    initial_coords = [geometry_.xy[1][0], geometry_.xy[0][0]]

    map_ = folium.Map(initial_coords, zoom_start=14)

    traces_json = json.loads(geometry.buffer(.00001).to_json())
    if (speed_color is not None):
        if (np.mean(speed_color) > 1):  # if absolute speeds
            red_speed, yellow_speed, blue_speed = 0, 25, 40
            cmap_caption = 'Speed Km/h'
        else:  # if relative speed
            red_speed, yellow_speed, blue_speed = 0, .4, .8
            cmap_caption = 'Relative Speed to Maximum %'

        speed_cm = LinearColormap(
            ['red', 'yellow', 'blue'],
            vmin=red_speed,
            vmax=blue_speed + (blue_speed * .2),  # 20% maxspeed
            index=[red_speed, yellow_speed, blue_speed])
        speed_cm.caption = cmap_caption

        for elem, speed in zip(traces_json['features'], speed_color):
            elem['properties']['style'] = {}
            elem['properties']['style']['color'] = speed_cm(speed)
            elem['properties']['style']['fillOpacity'] = 1

        map_.add_child(speed_cm)

    traces = folium.features.GeoJson(traces_json)
    map_.add_child(traces)
    return map_
Ejemplo n.º 4
0
    def getColor(self, feature):
        value = self.map_dict.get(feature['properties']['name'])
        self.color_scale = LinearColormap(['yellow', 'red'],
                                          vmin=min(self.map_dict.values()),
                                          vmax=max(self.map_dict.values()))
        # vmin = 0, vmax = 150)

        if value is None:
            return '#8c8c8c'  # MISSING -> gray
        else:
            return self.color_scale(value)
Ejemplo n.º 5
0
    def add_colorbar(
        self,
        colors,
        vmin=0,
        vmax=1.0,
        index=None,
        caption="",
        categorical=False,
        step=None,
        **kwargs,
    ):
        """Add a colorbar to the map.

        Args:
            colors (list): The set of colors to be used for interpolation. Colors can be provided in the form: * tuples of RGBA ints between 0 and 255 (e.g: (255, 255, 0) or (255, 255, 0, 255)) * tuples of RGBA floats between 0. and 1. (e.g: (1.,1.,0.) or (1., 1., 0., 1.)) * HTML-like string (e.g: “#ffff00) * a color name or shortcut (e.g: “y” or “yellow”)
            vmin (int, optional): The minimal value for the colormap. Values lower than vmin will be bound directly to colors[0].. Defaults to 0.
            vmax (float, optional): The maximal value for the colormap. Values higher than vmax will be bound directly to colors[-1]. Defaults to 1.0.
            index (list, optional):The values corresponding to each color. It has to be sorted, and have the same length as colors. If None, a regular grid between vmin and vmax is created.. Defaults to None.
            caption (str, optional): The caption for the colormap. Defaults to "".
            categorical (bool, optional): Whether or not to create a categorical colormap. Defaults to False.
            step (int, optional): The step to split the LinearColormap into a StepColormap. Defaults to None.
        """
        from box import Box
        from branca.colormap import LinearColormap

        if isinstance(colors, Box):
            try:
                colors = list(colors["default"])
            except Exception as e:
                print("The provided color list is invalid.")
                raise Exception(e)

        if all(len(color) == 6 for color in colors):
            colors = ["#" + color for color in colors]

        colormap = LinearColormap(colors=colors,
                                  index=index,
                                  vmin=vmin,
                                  vmax=vmax,
                                  caption=caption)

        if categorical:
            if step is not None:
                colormap = colormap.to_step(step)
            elif index is not None:
                colormap = colormap.to_step(len(index) - 1)
            else:
                colormap = colormap.to_step(3)

        self.add_child(colormap)
Ejemplo n.º 6
0
def color_scale(color1, color2, value, minValue, maxValue):
    """
    @param color1: This parameter is a string that contains a hexadecimal color (format #XXXXXX)
    or a valid color (for instance red, orange, yellow, blue) that establishes the first color
    in that range of values, the color that will be associated with minValue
    @param color2: This parameter is a string that contains a hexadecimal color (format #XXXXXX)
    or a valid color (for instance red, orange, yellow, blue) that establishes the second color
    in that range of values the color that will be associated with maxValue
    @param value: This parameter is a number, the value we have to paint with a color between
    color1 and color2 and that has to be between minValue and maxValue
    @param minValue: This parameter is a number, the lowest value possible within this range
    we are defining
    @param maxValue: This parameter is a number, the highest value possible within this range
    we are defining
    @return: LinearColorMap object
    
    Basically this builds an object where we build a color scale between two colors
    In minValue we indicate the value that represents color1 and in maxValue we indicate
    the value that represents color2 and we build a segment where the color of each
    value has a color according to that scale of value
    When we use it as a function using the parameter "value" we return the corresponding
    color for that value. We will use this function to color our map
    """
    return LinearColormap([color1, color2], vmin=minValue,
                          vmax=maxValue)(value)
Ejemplo n.º 7
0
    def __init__(self, max_value):
        """
        Initialize encode

        Args:
            max_value (float): maximum value for encoded features
        """
        self.cm = LinearColormap(["green", "yellow", "red"],
                                 vmin=0,
                                 vmax=max_value)
Ejemplo n.º 8
0
def color_scale(color1: str, color2: str, value: float, min_value: float,
                max_value: float) -> LinearColormap:
    """
    :param color1: This parameter is a string that contains a hexadecimal color (format #XXXXXX)
    or a valid color (for instance red, orange, yellow, blue) that establishes the first color
    in that range of values, the color that will be associated with minValue
    :param color2: This parameter is a string that contains a hexadecimal color (format #XXXXXX)
    or a valid color (for instance red, orange, yellow, blue) that establishes the second color
    in that range of values the color that will be associated with maxValue
    :param value: This parameter is a number, the value we have to paint with a color between
    color1 and color2 and that has to be between minValue and maxValue
    :param min_value: This parameter is a number, the lowest value possible within this range
    we are defining
    :param max_value: This parameter is a number, the highest value possible within this range
    we are defining
    :return: LinearColorMap object
    """
    return LinearColormap([color1, color2], vmin=min_value,
                          vmax=max_value)(value)
Ejemplo n.º 9
0
def map_points_circles(df, feature, date):

    print(feature.title(), 'at time:', date)

    # Create a map
    this_map = Map(prefer_canvas=True)

    # Check for the inputs to be on the dataframe
    # Getting data
    data = df[df['datetime'] == date]

    # Create a color map
    color_var = str(feature)  #what variable will determine the color
    cmap = LinearColormap(['blue', 'red'],
                          vmin=data[color_var].quantile(0.05),
                          vmax=data[color_var].quantile(0.95),
                          caption=color_var)

    # Add the color map legend to your map
    this_map.add_child(cmap)

    def plotDot(point):
        '''Takes a series that contains a list of floats named latitude and longitude and
         this function creates a CircleMarker and adds it to your this_map'''

        CircleMarker(location=[point.latitude, point.longitude],
                     fill_color=cmap(point[color_var]),
                     fill=True,
                     fill_opacity=0.4,
                     radius=40,
                     weight=0).add_to(this_map)

        # Iterate over rows

    data.apply(plotDot, axis=1)

    # Set the boundaries
    this_map.fit_bounds(this_map.get_bounds())

    # Show plot
    return this_map
Ejemplo n.º 10
0
def create_state_count_choropleth(df, designation):
    '''
    This function counts the number of parks per state and stores the
    result in a dataframe. Then it creates a linear color map using the
    range of parks per state. The function then reads in a GeoJSON file
    of the United States and merges this with the parks per state
    dataframe. These objects are then used to create a choropleth map
    of the United States with state color based on the number of parks
    in that state. If there are no parks in a state, it will be gray.

    Parameters
    ----------
    df : Pandas DataFrame
      DataFrame of all parks to add to the map.

    designation : str
      Designation of parks in the dataframe.

    Returns
    -------
    map : Folium map object
      Folium map with choropleth color added.
    '''

    # Create a two-column dataframe of state and a count of the number
    # of parks in that state.
    state_list = df['states'].apply(lambda x: x.split(','))
    state_list = reduce(operator.add, state_list)
    parks_per_state = (pd.DataFrame.from_dict(Counter(state_list),
                                              orient='index').reset_index())
    parks_per_state = (parks_per_state.rename(columns={
        'index': 'state',
        0: 'park_count'
    }))

    # Create the color map.
    color_scale = LinearColormap(['yellow', 'green', 'blue'],
                                 vmin=parks_per_state['park_count'].min(),
                                 vmax=parks_per_state['park_count'].max())
    color_scale.caption = (
        "Number of parks per state ({})".format(designation))

    # Create a dataframe from the json file using GeoPandas.
    df_geo = gpd.read_file('_reference_data/us-states.json')
    df_geo = df_geo.merge(parks_per_state,
                          left_on='id',
                          right_on='state',
                          how='left').fillna(0)

    # Find the center of the data and create an empty map.
    centroid = df_geo.geometry.centroid
    map = folium.Map(location=[centroid.y.mean(),
                               centroid.x.mean()],
                     zoom_start=3)

    # Color each state based on the number of parks in it.
    folium.GeoJson(
        data=df_geo[['geometry', 'name', 'state', 'park_count']],
        name='United States of America',
        style_function=lambda x: {
            'fillColor': get_state_color(x, parks_per_state, color_scale),
            'fillOpacity': 0.7,
            'color': 'black',
            'line_opacity': 0.5,
            'weight': 0.5
        },
        tooltip=folium.features.GeoJsonTooltip(fields=[
            'name',
            'park_count',
        ],
                                               aliases=["State", "# of parks"
                                                        ])).add_to(map)

    # Add color scale legend.
    map.add_child(color_scale)

    # Save choropleth to file.
    map.save(set_filename('choropleth_map', 'html', designation))

    return map
feq = feq.groupby('neighbourhood')['price'].mean().sort_values(ascending=True)
feq.plot.barh(figsize=(10, 8), color='b', width=1)
plt.title("Average daily price for a 2-persons accommodation", fontsize=20)
plt.xlabel('Average daily price (Euro)', fontsize=12)
plt.ylabel("")
plt.show()
adam = gpd.read_file("../input/neighbourhoods.geojson")
feq = pd.DataFrame([feq])
feq = feq.transpose()
adam = pd.merge(adam, feq, on='neighbourhood', how='left')
adam.rename(columns={'price': 'average_price'}, inplace=True)
adam.average_price = adam.average_price.round(decimals=0)

map_dict = adam.set_index('neighbourhood')['average_price'].to_dict()
color_scale = LinearColormap(['yellow', 'red'],
                             vmin=min(map_dict.values()),
                             vmax=max(map_dict.values()))


def get_color(feature):
    value = map_dict.get(feature['properties']['neighbourhood'])
    return color_scale(value)


map3 = folium.Map(location=[52.3680, 4.9036], zoom_start=11)
folium.GeoJson(data=adam,
               name='Amsterdam',
               tooltip=folium.features.GeoJsonTooltip(
                   fields=['neighbourhood', 'average_price'],
                   labels=True,
                   sticky=False),
Ejemplo n.º 12
0
                    'style': {
                        'color': row['Color']
                    }
                }
            }
            features.append(feature)
            if row["id"] in ["DNK", "FRA", "ITA", "GBR", "GRC"]:
                for geometry in compl.get(row["id"]).get("geometries"):
                    feature_new = dict(feature)
                    feature_new["geometry"] = geometry
                    features.append(feature_new)
    new_map = folium.Map([50.736455, 17.666], zoom_start=4.5)

    TimestampedGeoJson({
        'type': 'FeatureCollection',
        'features': features
    },
                       period='P1M',
                       duration='P1M',
                       add_last_point=True,
                       auto_play=False,
                       loop=False,
                       max_speed=1,
                       loop_button=True,
                       date_options='YYYY/MM',
                       time_slider_drag_update=True).add_to(new_map)
    colormap = LinearColormap(color_scale, vmin=0, vmax=bin_edges[-1])
    colormap.caption = "Monthly average " + pollutant + " (in µg/m3)"
    colormap.add_to(new_map)
    new_map.save("../maps/avg_" + pollutant + ".html")
Ejemplo n.º 13
0
    def loadChoroplethWorldCountries(self, filter):

        from copy import deepcopy
        import folium
        from branca.colormap import LinearColormap

        self.title = "World Choropleth"

        self.filter = deepcopy(filter)

        # find states in filtered sightings
        countryDict = defaultdict()

        minimalSightingList = self.mdiParent.db.GetMinimalFilteredSightingsList(
            filter)

        for s in minimalSightingList:

            # Consider only full species, not slash or spuh or hybrid entries
            commonName = s["commonName"]
            if "/" not in commonName and "sp." not in commonName and " x " not in commonName:

                if self.mdiParent.db.TestSighting(s, filter):

                    if s["country"] not in countryDict.keys():
                        countryDict[s["country"]] = [s]
                    else:
                        countryDict[s["country"]].append(s)

        # check if no sightings were found. Return false if none found. Abort and display message.
        if len(countryDict) == 0:
            return (False)

        countryTotals = defaultdict()
        largestTotal = 0
        for country in countryDict.keys():
            countrySpecies = set()
            for s in countryDict[country]:
                countrySpecies.add(s["commonName"])
            countryTotals[country] = len(countrySpecies)
            if len(countrySpecies) > largestTotal:
                largestTotal = len(countrySpecies)

        # Load the shape of the zone (US counties)
        geo_file = self.mdiParent.db.country_geo

        #add the country values to the geojson so we can access them for tooltips
        for f in geo_file["features"]:
            if f["id"] in countryTotals.keys():
                f["properties"]["speciesTotal"] = countryTotals[f["id"]]
            else:
                f["properties"]["speciesTotal"] = 0
                countryTotals[f["id"]] = 0

        #create color range for map, using the maximum country value found above
        colormap = LinearColormap(
            colors=[(255, 240, 227), (255, 119, 0)],
            index=[0, round(largestTotal * .75)],
            vmin=0,
            vmax=largestTotal,
        )

        # Initialize the folium map
        choro_map = folium.Map(location=[1, 1], zoom_start=1)

        # Configure the chloropleth layer and add to map
        folium.GeoJson(geo_file,
                       style_function=lambda feature: {
                           'fillColor':
                           'rgb(240, 240, 240)' if countryTotals[feature['id']]
                           == 0 else colormap(countryTotals[feature['id']]),
                           'color':
                           'black',
                           'weight':
                           1,
                           'fillOpacity':
                           .8,
                           'nan_fill_color':
                           'white'
                       },
                       tooltip=folium.features.GeoJsonTooltip(
                           fields=['name', 'speciesTotal'],
                           aliases=["Country", "Species"])).add_to(choro_map)

        # make the layer control box visible
        folium.LayerControl().add_to(choro_map)

        # get the html string from the map
        html = choro_map.get_root().render()

        self.webView.setHtml(html)

        return (True)
Ejemplo n.º 14
0
from branca.colormap import LinearColormap

color_scale = {}

lim1 = df2[[map_param]].rolling(smoothing).mean().fillna(0).describe().iloc[4,
                                                                            0]
lim2 = df2[[
    map_param
]].rolling(smoothing).mean().fillna(0).describe().iloc[[2, 1], 0].sum() * 5 / 3
diff = lim2 - lim1
color_scale = LinearColormap([
    '#91db9b',
    'yellow',
    'red',
],
                             index=[
                                 max(0, lim1 - diff / 2),
                                 max(0, lim1 - min(lim1 / 2, diff / 2)),
                                 lim2 - diff / 6
                             ])

feature_group5 = folium.FeatureGroup(name='Area of interest', show=True)


def plotDot(point, color):
    size = 2
    if smoothing:
        to_plot = 'smoothedmap'
    else:
        if map_param == 'SCRIM':
            to_plot = 'THRESHOLD1'
Ejemplo n.º 15
0
fillColours = colours['Colours'].values.tolist()
colours = colours.merge(mostPopularByZIP,
                        'left').drop_duplicates(subset='Breed Numeric').drop(
                            ['Count', 'ZIP Code'], axis=1)

mostPopularByZIP = mostPopularByZIP.merge(colours, how='left')

#add in seaborn summarized plots to map

dictMPBZ = mostPopularByZIP[['Breed Numeric', 'ZIP Code']]
dictMPBZ = dictMPBZ.reset_index()
dictMPBZ['Breed ZIP'] = dictMPBZ[['Breed Numeric', 'ZIP Code']].values.tolist()

color_scale = LinearColormap(fillColours,
                             vmin=dictMPBZ['Breed Numeric'].min(),
                             vmax=dictMPBZ['Breed Numeric'].max())


def get_color(feature):
    for i, r in dictMPBZ.iterrows():
        if feature['properties']['postalCode'] == r['Breed ZIP'][1]:
            return color_scale(r['Breed ZIP'][0])


folium.GeoJson(data='~/DS projects/Dog map/filtered-file.geojson',
               style_function=lambda feature: {
                   'fillColor': get_color(feature),
                   'fillOpacity': 0.8,
                   'color': 'black',
                   'weight': 1,
Ejemplo n.º 16
0
bands[4] = {'LV3':[5,13], 'LV10':[27,71], 'LTRC':[0.15, 2.0], 'LLTX':[0.6, 0.3], 'LLRD':[10, 20], 'LRRD':[10, 20], 'RCI':[40, 100]}
bands[5] = {'LV3':[7,17], 'LV10':[35,93], 'LTRC':[0.15, 2.0], 'LLTX':[0.6, 0.3], 'LLRD':[10, 20], 'LRRD':[10, 20], 'RCI':[40, 100]}
bands[6] = {'LV3':[8,20], 'LV10':[41,110], 'LTRC':[0.15, 2.0], 'LLTX':[0.6, 0.3], 'LLRD':[10, 20], 'LRRD':[10, 20], 'RCI':[40, 100]}


from branca.colormap import LinearColormap

color_scale = {}

if hier in bands:  
   if map_param in bands[hier]:
       lim1 = bands[hier][map_param][0]
       lim2 = bands[hier][map_param][1]
       diff = lim2-lim1
       if diff > 0:
           color_scale = LinearColormap(['#91db9b','yellow','red',], index=[max(0,lim1-diff/2),max(0,lim1-min(lim1/2,diff/2)),lim2-diff/6])
       else: #texture
           color_scale = LinearColormap(['red','yellow','#91db9b',], index=[lim2+diff/6,lim1+diff/2,max(0,lim1-diff/2),])
       
       #st.write('limits are %s , %s , %s. %s %s' %(max(0,lim1-diff/2),lim1+diff/2,lim2+diff/6, lim1, lim2))

   elif map_param == 'SCRIM':
       color_scale = LinearColormap(['#91db9b','yellow','red'], index=[0.005,0.05,0.13])            
   else:
       #df_tmp = df3[map_param].append(df4[map_param])
       lim1 = df[df['Class']==hier][[map_param]].describe().iloc[4,0]
       lim2 = df[df['Class']==hier][[map_param]].describe().iloc[[2,1],0].sum()*5/3
       diff = lim2-lim1
       color_scale = LinearColormap(['#91db9b','yellow','red',], index=[lim1,lim2-diff/2,lim2-diff/6])       
       #st.write('limits are %s , %s , %s. %s %s' %( lim1,lim1+diff/6,lim2-diff/6, lim1, lim2))
       
Ejemplo n.º 17
0
class WorldMapDisplay():
    def __init__(self, countries, cumul_or_diff, which_data):
        self.geolocator = Nominatim(
            user_agent="Worldmap for Covid-19 studing case")
        # ,tiles="cartodbpositron")#,"CartoDB dark_matter")
        self.world_map = folium.Map(width=600,
                                    height=400,
                                    location=[48.52, 2.19],
                                    zoom_start=3)
        self.countries = sorted(countries)
        self.which_data = which_data
        p = cc.Parser()
        babypandas = (p.getStats(country=self.countries,
                                 type=cumul_or_diff,
                                 which=which_data,
                                 output='pandas'))
        babypandascumul = babypandas
        babypandascumul['cumul'] = babypandas.groupby(
            ['country'])['cases'].apply(lambda x: x.cumsum())

        mask_date_max = babypandas.groupby(['country'])['date'].max()
        babypandascumulmasked_date = babypandascumul['date'].isin(
            mask_date_max)
        self.data = pd.pivot_table(babypandas,
                                   index='date',
                                   columns='country',
                                   values='cases').reset_index()
        if cumul_or_diff == 'cumul':
            self.data = pd.pivot_table(babypandascumul,
                                       index='date',
                                       columns='country',
                                       values='cumul').reset_index()

        map_data = pd.DataFrame({
            'country':
            self.countries,
            'totcases':
            babypandascumul[babypandascumulmasked_date]['cumul'].to_list()
        })
        self.totalsallcountries = sum(
            babypandascumul[babypandascumulmasked_date]['cumul'])
        self.maxdeaths = max(
            babypandascumul[babypandascumulmasked_date]['cumul'])
        self.map_dict = map_data.set_index('country')['totcases'].to_dict()

    def LatLong(self, country):
        if country != None:
            location = self.geolocator.geocode(country)
            if location != None:
                Lat = location.latitude  # , location.longitude)
                Long = location.longitude
            else:
                Lat = float("Nan")  # , location.longitude)
                Long = float("Nan")
        return (Lat, Long)

    def DrawPopUpCircle(self):
        for coun in self.countries:
            filter_data = self.data[['date',
                                     coun]].rename(columns={coun: 'cases'})
            tot = self.map_dict[coun]
            latlong = self.LatLong(coun)
            start_coords = [latlong[0], latlong[1]]
            source = pd.DataFrame({
                'date': filter_data['date'],
                'cases': filter_data['cases'],
            })
            if sum(filter_data['cases']) != 0:
                chart = alt.Chart(source).mark_line().encode(
                    alt.X('date', axis=alt.Axis(title='Date')),
                    alt.Y('cases', axis=alt.Axis(title='Cases'))).properties(
                        title=coun.upper())
                vis1 = chart.to_json()
                vega = folium.features.VegaLite(vis1,
                                                width='100%',
                                                height='100%')

                #
                maxrad = 50
                circ_mkr = folium.CircleMarker(
                    location=start_coords,
                    radius=maxrad * tot / self.totalsallcountries,
                    color='blue',
                    fill=True,
                    fill_color='red',
                    fillOpacity=1.0,
                    opacity=1.0,
                    tooltip=coun,
                    popup=folium.Popup(max_width=300).add_child(vega))
                circ_mkr.add_to(self.world_map)

    def drawCountry(self):
        folium.GeoJson(
            data=
            'https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json',
            style_function=lambda feature: {
                'fillColor': self.getColor(feature),
                'caption': 'Total deaths',
                'fillOpacity': 0.5,
                'weight': 0.5
            }).add_to(self.world_map)

    def getColor(self, feature):
        value = self.map_dict.get(feature['properties']['name'])
        self.color_scale = LinearColormap(['yellow', 'red'],
                                          vmin=min(self.map_dict.values()),
                                          vmax=max(self.map_dict.values()))
        # vmin = 0, vmax = 150)

        if value is None:
            return '#8c8c8c'  # MISSING -> gray
        else:
            return self.color_scale(value)

    def returnMap(self):
        self.drawCountry()
        self.DrawPopUpCircle()
        colormap = self.color_scale.to_step(len(self.countries))
        colormap.caption = self.which_data.upper()
        self.world_map.add_child(colormap)
        return self.world_map
Ejemplo n.º 18
0
def geo_map(h2,
            map=None,
            tiles='stamenterrain',
            cmap="wk",
            alpha=0.5,
            lw=1,
            fit_bounds=None,
            layer_name=None):
    """Show rectangular grid over a map.

    Parameters
    ----------
    h2: physt.histogram_nd.Histogram2D
        A histogram of coordinates (in degrees: latitude, longitude)
    map : folium.folium.Map

    Returns
    -------
    map : folium.folium.Map
    """
    if not map:
        latitude = h2.get_bin_centers(0).mean()
        longitude = h2.get_bin_centers(1).mean()
        zoom_start = 10
        map = folium.Map(location=[latitude, longitude], tiles=tiles)
        if fit_bounds == None:
            fit_bounds = True

    geo_json = _bins_to_json(h2)

    if not layer_name:
        layer_name = h2.name

    from branca.colormap import LinearColormap

    color_map = LinearColormap(cmap,
                               vmin=h2.frequencies.min(),
                               vmax=h2.frequencies.max())

    # legend = folium.Html("<div>Legend</div>")
    # legend_div = folium.Div("20%", "20%", "75%", "5%")
    #
    # legend_div.add_to(map)
    # legend_div.add_child(legend)

    #xx = h2.frequencies.max()

    def styling_function(bin):
        count = bin["properties"]["count"]
        return {
            "fillColor": color_map(count),
            "color": "black",
            "fillOpacity": alpha if count > 0 else 0,
            "weight": lw,
            # "strokeWidth": lw,
            "opacity": alpha if count > 0 else 0,
        }  # .update(styling)

    layer = folium.GeoJson(geo_json,
                           style_function=styling_function,
                           name=layer_name)
    layer.add_to(map)
    if fit_bounds:
        map.fit_bounds(layer.get_bounds())
    return map
Ejemplo n.º 19
0
    def colorMap_Linear(self,
                        column1,
                        column2=None,
                        threshold_min1=None,
                        threshold_min2=None,
                        threshold_max1=None,
                        threshold_max2=None,
                        method='linear'):
        """Creates a colormap for the Choropleth map.

        Parameters
        ----------
        column1 : Attribute that specifies the fill colour of the Choropleth map

        column2 : Attribute that spceifies the border colour of the Choropleth map

        Examples
        --------
        >>> geo.colorMap('Population', 'PopDensity')

        """

        if threshold_min1 == None:
            threshold_min1 = self.df[column1].min()
        if threshold_max1 == None:
            threshold_max1 = self.df[column1].max()
        self.column1 = column1
        self.colormap = LinearColormap(
            ['#3f372f', '#62c1a6', '#1b425e', '#bbf9d9', '#ffffff'],
            vmin=self.df[self.df[column1] >= threshold_min1][column1].min(),
            vmax=self.df[
                self.df[column1] <= threshold_max1][column1].max()).to_step(
                    data=self.df[self.df[column1] <= threshold_max1][
                        self.df[column1] >= 0][column1],
                    n=5,
                    method=method)
        self.vdict = self.df[self.df[column1] <= threshold_max1][
            self.df[column1] >= threshold_min1].set_index(
                self.locationcol)[column1]
        self.baseMap.map.add_child(self.colormap)
        self.baseMap.map.add_child(
            BindColormap(
                self.baseMap.feature_groups[self.feature_group][self.name],
                self.colormap))

        if column2 == None:
            self.colormap2 = None
        else:
            if threshold_min2 == None:
                threshold_min2 = self.df[column2].min()
            if threshold_max2 == None:
                threshold_max2 = self.df[column2].max()
            self.column2 = column2
            self.colormap2 = LinearColormap(
                ['#3f372f', '#62c1a6', '#1b425e', '#bbf9d9', '#ffffff'],
                vmin=self.df[
                    self.df[column2] >= threshold_min2][column2].min(),
                vmax=self.df[self.df[column2] <= threshold_max2]
                [column2].max()).to_step(
                    data=self.df[self.df[column2] <= threshold_max2][
                        self.df[column2] >= 0][column2],
                    n=5,
                    method=method)
            self.vdict2 = self.df[self.df[column2] <= threshold_max2][
                self.df[column2] >= threshold_min2].set_index(
                    self.locationcol)[column2]
            self.baseMap.map.add_child(self.colormap2)
            self.baseMap.map.add_child(
                BindColormap(
                    self.baseMap.feature_groups[self.feature_group][self.name],
                    self.colormap2))