geemap/geemap.py
def add_colorbar(
        self,
        vis_params=None,
        cmap="gray",
        discrete=False,
        label=None,
        orientation="horizontal",
        position="bottomright",
        transparent_bg=False,
        layer_name=None,
        **kwargs,
    ):
        """Add a matplotlib colorbar to the map

        Args:
            vis_params (dict): Visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options.
            cmap (str, optional): Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.
            discrete (bool, optional): Whether to create a discrete colorbar. Defaults to False.
            label (str, optional): Label for the colorbar. Defaults to None.
            orientation (str, optional): Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".
            position (str, optional): Position of the colorbar on the map. It can be one of: topleft, topright, bottomleft, and bottomright. Defaults to "bottomright".
            transparent_bg (bool, optional): Whether to use transparent background. Defaults to False.
            layer_name (str, optional): The layer name associated with the colorbar. Defaults to None.

        Raises:
            TypeError: If the vis_params is not a dictionary.
            ValueError: If the orientation is not either horizontal or vertical.
            ValueError: If the provided min value is not scalar type.
            ValueError: If the provided max value is not scalar type.
            ValueError: If the provided opacity value is not scalar type.
            ValueError: If cmap or palette is not provided.
        """
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        import numpy as np

        if isinstance(vis_params, list):
            vis_params = {"palette": vis_params}
        elif isinstance(vis_params, tuple):
            vis_params = {"palette": list(vis_params)}
        elif vis_params is None:
            vis_params = {}

        if "colors" in kwargs and isinstance(kwargs["colors"], list):
            vis_params["palette"] = kwargs["colors"]

        if "colors" in kwargs and isinstance(kwargs["colors"], tuple):
            vis_params["palette"] = list(kwargs["colors"])

        if "vmin" in kwargs:
            vis_params["min"] = kwargs["vmin"]
            del kwargs["vmin"]

        if "vmax" in kwargs:
            vis_params["max"] = kwargs["vmax"]
            del kwargs["vmax"]

        if "caption" in kwargs:
            label = kwargs["caption"]
            del kwargs["caption"]

        if not isinstance(vis_params, dict):
            raise TypeError("The vis_params must be a dictionary.")

        if orientation not in ["horizontal", "vertical"]:
            raise ValueError("The orientation must be either horizontal or vertical.")

        if orientation == "horizontal":
            width, height = 6.0, 0.4
        else:
            width, height = 0.4, 4.0

        if "width" in kwargs:
            width = kwargs["width"]
            kwargs.pop("width")

        if "height" in kwargs:
            height = kwargs["height"]
            kwargs.pop("height")

        vis_keys = list(vis_params.keys())

        if "min" in vis_params:
            vmin = vis_params["min"]
            if type(vmin) not in (int, float):
                raise ValueError("The provided min value must be scalar type.")
        else:
            vmin = 0

        if "max" in vis_params:
            vmax = vis_params["max"]
            if type(vmax) not in (int, float):
                raise ValueError("The provided max value must be scalar type.")
        else:
            vmax = 1

        if "opacity" in vis_params:
            alpha = vis_params["opacity"]
            if type(alpha) not in (int, float):
                raise ValueError("The provided opacity value must be type scalar.")
        elif "alpha" in kwargs:
            alpha = kwargs["alpha"]
        else:
            alpha = 1

        if cmap is not None:

            cmap = mpl.pyplot.get_cmap(cmap)
            norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

        if "palette" in vis_keys:
            hexcodes = to_hex_colors(vis_params["palette"])
            if discrete:
                cmap = mpl.colors.ListedColormap(hexcodes)
                vals = np.linspace(vmin, vmax, cmap.N + 1)
                norm = mpl.colors.BoundaryNorm(vals, cmap.N)

            else:
                cmap = mpl.colors.LinearSegmentedColormap.from_list(
                    "custom", hexcodes, N=256
                )
                norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

        elif cmap is not None:

            cmap = mpl.pyplot.get_cmap(cmap)
            norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

        else:
            raise ValueError(
                'cmap keyword or "palette" key in vis_params must be provided.'
            )

        _, ax = plt.subplots(figsize=(width, height))
        cb = mpl.colorbar.ColorbarBase(
            ax, norm=norm, alpha=alpha, cmap=cmap, orientation=orientation, **kwargs
        )

        if "bands" in vis_keys:
            cb.set_label(vis_params["bands"])
        elif label is not None:
            cb.set_label(label)

        output = widgets.Output()
        colormap_ctrl = ipyleaflet.WidgetControl(
            widget=output,
            position=position,
            transparent_bg=transparent_bg,
        )
        with output:
            output.clear_output()
            plt.show()

        self.colorbar = colormap_ctrl
        if layer_name in self.ee_layer_names:
            if "colorbar" in self.ee_layer_dict[layer_name]:
                self.remove_control(self.ee_layer_dict[layer_name]["colorbar"])
            self.ee_layer_dict[layer_name]["colorbar"] = colormap_ctrl
        if not hasattr(self, "colorbars"):
            self.colorbars = [colormap_ctrl]
        else:
            self.colorbars.append(colormap_ctrl)

        self.add_control(colormap_ctrl)
Add a matplotlib colorbar to the map

        Args:
            vis_params (dict): Visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options.
            cmap (str, optional): Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.
            discrete (bool, optional): Whether to create a discrete colorbar. Defaults to False.
            label (str, optional): Label for the colorbar. Defaults to None.
            orientation (str, optional): Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".
            position (str, optional): Position of the colorbar on the map. It can be one of: topleft, topright, bottomleft, and bottomright. Defaults to "bottomright".
            transparent_bg (bool, optional): Whether to use transparent background. Defaults to False.
            layer_name (str, optional): The layer name associated with the colorbar. Defaults to None.

        Raises:
            TypeError: If the vis_params is not a dictionary.
            ValueError: If the orientation is not either horizontal or vertical.
            ValueError: If the provided min value is not scalar type.
            ValueError: If the provided max value is not scalar type.
            ValueError: If the provided opacity value is not scalar type.
            ValueError: If cmap or palette is not provided.
        
Add a matplotlib colorbar to the map
Add a matplotlib colorbar to the map
def add_colorbar(
        self,
        vis_params=None,
        cmap="gray",
        discrete=False,
        label=None,
        orientation="horizontal",
        position="bottomright",
        transparent_bg=False,
        layer_name=None,
        **kwargs,
    ):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        import numpy as np
        if isinstance(vis_params, list):
            vis_params = {"palette": vis_params}
        elif isinstance(vis_params, tuple):
            vis_params = {"palette": list(vis_params)}
        elif vis_params is None:
            vis_params = {}
        if "colors" in kwargs and isinstance(kwargs["colors"], list):
            vis_params["palette"] = kwargs["colors"]
        if "colors" in kwargs and isinstance(kwargs["colors"], tuple):
            vis_params["palette"] = list(kwargs["colors"])
        if "vmin" in kwargs:
            vis_params["min"] = kwargs["vmin"]
            del kwargs["vmin"]
        if "vmax" in kwargs:
            vis_params["max"] = kwargs["vmax"]
            del kwargs["vmax"]
        if "caption" in kwargs:
            label = kwargs["caption"]
            del kwargs["caption"]
        if not isinstance(vis_params, dict):
            raise TypeError("The vis_params must be a dictionary.")
        if orientation not in ["horizontal", "vertical"]:
            raise ValueError("The orientation must be either horizontal or vertical.")
        if orientation == "horizontal":
            width, height = 6.0, 0.4
        else:
            width, height = 0.4, 4.0
        if "width" in kwargs:
            width = kwargs["width"]
            kwargs.pop("width")
        if "height" in kwargs:
            height = kwargs["height"]
            kwargs.pop("height")
        vis_keys = list(vis_params.keys())
        if "min" in vis_params:
            vmin = vis_params["min"]
            if type(vmin) not in (int, float):
                raise ValueError("The provided min value must be scalar type.")
        else:
            vmin = 0
        if "max" in vis_params:
            vmax = vis_params["max"]
            if type(vmax) not in (int, float):
                raise ValueError("The provided max value must be scalar type.")
        else:
            vmax = 1
        if "opacity" in vis_params:
            alpha = vis_params["opacity"]
            if type(alpha) not in (int, float):
                raise ValueError("The provided opacity value must be type scalar.")
        elif "alpha" in kwargs:
            alpha = kwargs["alpha"]
        else:
            alpha = 1
        if cmap is not None:
            cmap = mpl.pyplot.get_cmap(cmap)
            norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
        if "palette" in vis_keys:
            hexcodes = to_hex_colors(vis_params["palette"])
            if discrete:
                cmap = mpl.colors.ListedColormap(hexcodes)
                vals = np.linspace(vmin, vmax, cmap.N + 1)
                norm = mpl.colors.BoundaryNorm(vals, cmap.N)
            else:
                cmap = mpl.colors.LinearSegmentedColormap.from_list(
                    "custom", hexcodes, N=256
                )
                norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
        elif cmap is not None:
            cmap = mpl.pyplot.get_cmap(cmap)
            norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
        else:
            raise ValueError(
                'cmap keyword or "palette" key in vis_params must be provided.'
            )
        _, ax = plt.subplots(figsize=(width, height))
        cb = mpl.colorbar.ColorbarBase(
            ax, norm=norm, alpha=alpha, cmap=cmap, orientation=orientation, **kwargs
        )
        if "bands" in vis_keys:
            cb.set_label(vis_params["bands"])
        elif label is not None:
            cb.set_label(label)
        output = widgets.Output()
        colormap_ctrl = ipyleaflet.WidgetControl(
            widget=output,
            position=position,
            transparent_bg=transparent_bg,
        )
        with output:
            output.clear_output()
            plt.show()
        self.colorbar = colormap_ctrl
        if layer_name in self.ee_layer_names:
            if "colorbar" in self.ee_layer_dict[layer_name]:
                self.remove_control(self.ee_layer_dict[layer_name]["colorbar"])
            self.ee_layer_dict[layer_name]["colorbar"] = colormap_ctrl
        if not hasattr(self, "colorbars"):
            self.colorbars = [colormap_ctrl]
        else:
            self.colorbars.append(colormap_ctrl)
        self.add_control(colormap_ctrl)
def add_colorbar ( self , vis_params = None , cmap = "gray" , discrete = False , label = None , orientation = "horizontal" , position = "bottomright" , transparent_bg = False , layer_name = None , ** kwargs , ) : import matplotlib as mpl import matplotlib . pyplot as plt import numpy as np if isinstance ( vis_params , list ) : vis_params = { "palette" : vis_params } elif isinstance ( vis_params , tuple ) : vis_params = { "palette" : list ( vis_params ) } elif vis_params is None : vis_params = { } if "colors" in kwargs and isinstance ( kwargs [ "colors" ] , list ) : vis_params [ "palette" ] = kwargs [ "colors" ] if "colors" in kwargs and isinstance ( kwargs [ "colors" ] , tuple ) : vis_params [ "palette" ] = list ( kwargs [ "colors" ] ) if "vmin" in kwargs : vis_params [ "min" ] = kwargs [ "vmin" ] del kwargs [ "vmin" ] if "vmax" in kwargs : vis_params [ "max" ] = kwargs [ "vmax" ] del kwargs [ "vmax" ] if "caption" in kwargs : label = kwargs [ "caption" ] del kwargs [ "caption" ] if not isinstance ( vis_params , dict ) : raise TypeError ( "The vis_params must be a dictionary." ) if orientation not in [ "horizontal" , "vertical" ] : raise ValueError ( "The orientation must be either horizontal or vertical." ) if orientation == "horizontal" : width , height = 6.0 , 0.4 else : width , height = 0.4 , 4.0 if "width" in kwargs : width = kwargs [ "width" ] kwargs . pop ( "width" ) if "height" in kwargs : height = kwargs [ "height" ] kwargs . pop ( "height" ) vis_keys = list ( vis_params . keys ( ) ) if "min" in vis_params : vmin = vis_params [ "min" ] if type ( vmin ) not in ( int , float ) : raise ValueError ( "The provided min value must be scalar type." ) else : vmin = 0 if "max" in vis_params : vmax = vis_params [ "max" ] if type ( vmax ) not in ( int , float ) : raise ValueError ( "The provided max value must be scalar type." ) else : vmax = 1 if "opacity" in vis_params : alpha = vis_params [ "opacity" ] if type ( alpha ) not in ( int , float ) : raise ValueError ( "The provided opacity value must be type scalar." ) elif "alpha" in kwargs : alpha = kwargs [ "alpha" ] else : alpha = 1 if cmap is not None : cmap = mpl . pyplot . get_cmap ( cmap ) norm = mpl . colors . Normalize ( vmin = vmin , vmax = vmax ) if "palette" in vis_keys : hexcodes = to_hex_colors ( vis_params [ "palette" ] ) if discrete : cmap = mpl . colors . ListedColormap ( hexcodes ) vals = np . linspace ( vmin , vmax , cmap . N + 1 ) norm = mpl . colors . BoundaryNorm ( vals , cmap . N ) else : cmap = mpl . colors . LinearSegmentedColormap . from_list ( "custom" , hexcodes , N = 256 ) norm = mpl . colors . Normalize ( vmin = vmin , vmax = vmax ) elif cmap is not None : cmap = mpl . pyplot . get_cmap ( cmap ) norm = mpl . colors . Normalize ( vmin = vmin , vmax = vmax ) else : raise ValueError ( 'cmap keyword or "palette" key in vis_params must be provided.' ) _ , ax = plt . subplots ( figsize = ( width , height ) ) cb = mpl . colorbar . ColorbarBase ( ax , norm = norm , alpha = alpha , cmap = cmap , orientation = orientation , ** kwargs ) if "bands" in vis_keys : cb . set_label ( vis_params [ "bands" ] ) elif label is not None : cb . set_label ( label ) output = widgets . Output ( ) colormap_ctrl = ipyleaflet . WidgetControl ( widget = output , position = position , transparent_bg = transparent_bg , ) with output : output . clear_output ( ) plt . show ( ) self . colorbar = colormap_ctrl if layer_name in self . ee_layer_names : if "colorbar" in self . ee_layer_dict [ layer_name ] : self . remove_control ( self . ee_layer_dict [ layer_name ] [ "colorbar" ] ) self . ee_layer_dict [ layer_name ] [ "colorbar" ] = colormap_ctrl if not hasattr ( self , "colorbars" ) : self . colorbars = [ colormap_ctrl ] else : self . colorbars . append ( colormap_ctrl ) self . add_control ( colormap_ctrl )
Add a matplotlib colorbar to the map
Add a matplotlib colorbar to the map
"""Add a matplotlib colorbar to the map

        Args:
            vis_params (dict): Visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options.
            cmap (str, optional): Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.
            discrete (bool, optional): Whether to create a discrete colorbar. Defaults to False.
            label (str, optional): Label for the colorbar. Defaults to None.
            orientation (str, optional): Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".
            position (str, optional): Position of the colorbar on the map. It can be one of: topleft, topright, bottomleft, and bottomright. Defaults to "bottomright".
            transparent_bg (bool, optional): Whether to use transparent background. Defaults to False.
            layer_name (str, optional): The layer name associated with the colorbar. Defaults to None.

        Raises:
            TypeError: If the vis_params is not a dictionary.
            ValueError: If the orientation is not either horizontal or vertical.
            ValueError: If the provided min value is not scalar type.
            ValueError: If the provided max value is not scalar type.
            ValueError: If the provided opacity value is not scalar type.
            ValueError: If cmap or palette is not provided.
        """
If the vis_params is not a dictionary.
If the vis_params is not a dictionary .
TypeError
If the orientation is not either horizontal or vertical.
If the orientation is not either horizontal or vertical .
ValueError
If the provided min value is not scalar type.
If the provided min value is not scalar type .
ValueError
If the provided max value is not scalar type.
If the provided max value is not scalar type .
ValueError
If the provided opacity value is not scalar type.
If the provided opacity value is not scalar type .
ValueError
If cmap or palette is not provided.
If cmap or palette is not provided .
ValueError
self
vis_params
Visualization parameters as a dictionary.
Visualization parameters as a dictionary .
cmap
Matplotlib colormap. Defaults to "gray".
Matplotlib colormap . Defaults to " gray " .
"gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options
discrete
Whether to create a discrete colorbar. Defaults to False.
Whether to create a discrete colorbar . Defaults to False .
False
label
Label for the colorbar. Defaults to None.
Label for the colorbar . Defaults to None .
None
orientation
Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".
Orientation of the colorbar such as " vertical " and " horizontal " . Defaults to " horizontal " .
"horizontal"
position
Position of the colorbar on the map. It can be one of: topleft, topright, bottomleft, and bottomright. Defaults to "bottomright".
Position of the colorbar on the map . It can be one of : topleft topright bottomleft and bottomright . Defaults to " bottomright " .
"bottomright"
transparent_bg
Whether to use transparent background. Defaults to False.
Whether to use transparent background . Defaults to False .
False
layer_name
The layer name associated with the colorbar. Defaults to None.
The layer name associated with the colorbar . Defaults to None .
None