Пример #1
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)
Пример #2
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