Skip to content

chart module

Module for creating charts from Earth Engine data.

BarChart

Bases: BaseChartClass

Create Bar Chart. All histogram/bar charts can use this object.

Source code in geemap/chart.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
class BarChart(BaseChartClass):
    """Create Bar Chart. All histogram/bar charts can use this object."""

    def __init__(
        self,
        features: Union[ee.FeatureCollection, pd.DataFrame],
        default_labels: List[str],
        name: str,
        type: str = "grouped",
        **kwargs: Any,
    ):
        """
        Initializes the BarChart with the given features, labels, name, and type.

        Args:
            features (ee.FeatureCollection | pd.DataFrame): The features to plot.
            default_labels (List[str]): The default labels for the chart.
            name (str): The name of the chart.
            type (str, optional): The type of bar chart ('grouped' or 'stacked').
                Defaults to 'grouped'.
            **kwargs: Additional keyword arguments to set as attributes.
        """
        super().__init__(features, default_labels, name, **kwargs)
        self.type: str = type

    def generate_tooltip(self) -> None:
        """
        Generates a tooltip for the bar chart.
        """
        if (self.x_label is not None) and (self.y_label is not None):
            self.bar_chart.tooltip = Tooltip(
                fields=["x", "y"], labels=[self.x_label, self.y_label]
            )
        else:
            self.bar_chart.tooltip = Tooltip(fields=["x", "y"])

    def get_ylim(self) -> Tuple[float, float]:
        """
        Gets the y-axis limits for the bar chart.

        Returns:
            Tuple[float, float]: The minimum and maximum y-axis limits.
        """
        if self.ylim:
            ylim_min, ylim_max = self.ylim[0], self.ylim[1]
        else:
            if self.name in ["feature.byFeature", "feature.byProperty"]:
                ylim_min = np.min(self.y_data)
                ylim_max = np.max(self.y_data) + 0.2 * (
                    np.max(self.y_data) - np.min(self.y_data)
                )
            if self.name in ["feature.groups"]:
                ylim_min = np.min(self.df[self.yProperty])
                ylim_max = np.max(self.df[self.yProperty])
                ylim_max = ylim_max + 0.2 * (ylim_max - ylim_min)
        return (ylim_min, ylim_max)

    def plot_chart(self) -> None:
        """
        Plots the bar chart.
        """
        fig = plt.figure(
            title=self.title,
            legend_location=self.legend_location,
        )

        self.bar_chart = plt.bar(
            self.x_data,
            self.y_data,
            labels=self.labels,
            display_legend=self.display_legend,
        )

        self.generate_tooltip()
        plt.ylim(*self.get_ylim())
        if self.x_label:
            plt.xlabel(self.x_label)
        if self.y_label:
            plt.ylabel(self.y_label)

        if self.width:
            fig.layout.width = self.width
        if self.height:
            fig.layout.height = self.height

        self.bar_chart.colors = self.colors
        self.bar_chart.type = self.type

        plt.show()

__init__(features, default_labels, name, type='grouped', **kwargs)

Initializes the BarChart with the given features, labels, name, and type.

Parameters:

Name Type Description Default
features FeatureCollection | DataFrame

The features to plot.

required
default_labels List[str]

The default labels for the chart.

required
name str

The name of the chart.

required
type str

The type of bar chart ('grouped' or 'stacked'). Defaults to 'grouped'.

'grouped'
**kwargs Any

Additional keyword arguments to set as attributes.

{}
Source code in geemap/chart.py
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def __init__(
    self,
    features: Union[ee.FeatureCollection, pd.DataFrame],
    default_labels: List[str],
    name: str,
    type: str = "grouped",
    **kwargs: Any,
):
    """
    Initializes the BarChart with the given features, labels, name, and type.

    Args:
        features (ee.FeatureCollection | pd.DataFrame): The features to plot.
        default_labels (List[str]): The default labels for the chart.
        name (str): The name of the chart.
        type (str, optional): The type of bar chart ('grouped' or 'stacked').
            Defaults to 'grouped'.
        **kwargs: Additional keyword arguments to set as attributes.
    """
    super().__init__(features, default_labels, name, **kwargs)
    self.type: str = type

generate_tooltip()

Generates a tooltip for the bar chart.

Source code in geemap/chart.py
612
613
614
615
616
617
618
619
620
621
def generate_tooltip(self) -> None:
    """
    Generates a tooltip for the bar chart.
    """
    if (self.x_label is not None) and (self.y_label is not None):
        self.bar_chart.tooltip = Tooltip(
            fields=["x", "y"], labels=[self.x_label, self.y_label]
        )
    else:
        self.bar_chart.tooltip = Tooltip(fields=["x", "y"])

get_ylim()

Gets the y-axis limits for the bar chart.

Returns:

Type Description
Tuple[float, float]

Tuple[float, float]: The minimum and maximum y-axis limits.

Source code in geemap/chart.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
def get_ylim(self) -> Tuple[float, float]:
    """
    Gets the y-axis limits for the bar chart.

    Returns:
        Tuple[float, float]: The minimum and maximum y-axis limits.
    """
    if self.ylim:
        ylim_min, ylim_max = self.ylim[0], self.ylim[1]
    else:
        if self.name in ["feature.byFeature", "feature.byProperty"]:
            ylim_min = np.min(self.y_data)
            ylim_max = np.max(self.y_data) + 0.2 * (
                np.max(self.y_data) - np.min(self.y_data)
            )
        if self.name in ["feature.groups"]:
            ylim_min = np.min(self.df[self.yProperty])
            ylim_max = np.max(self.df[self.yProperty])
            ylim_max = ylim_max + 0.2 * (ylim_max - ylim_min)
    return (ylim_min, ylim_max)

plot_chart()

Plots the bar chart.

Source code in geemap/chart.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def plot_chart(self) -> None:
    """
    Plots the bar chart.
    """
    fig = plt.figure(
        title=self.title,
        legend_location=self.legend_location,
    )

    self.bar_chart = plt.bar(
        self.x_data,
        self.y_data,
        labels=self.labels,
        display_legend=self.display_legend,
    )

    self.generate_tooltip()
    plt.ylim(*self.get_ylim())
    if self.x_label:
        plt.xlabel(self.x_label)
    if self.y_label:
        plt.ylabel(self.y_label)

    if self.width:
        fig.layout.width = self.width
    if self.height:
        fig.layout.height = self.height

    self.bar_chart.colors = self.colors
    self.bar_chart.type = self.type

    plt.show()

BaseChartClass

This should include everything a chart module requires to plot figures.

Source code in geemap/chart.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
class BaseChartClass:
    """This should include everything a chart module requires to plot figures."""

    def __init__(
        self,
        features: Union[ee.FeatureCollection, pd.DataFrame],
        default_labels: List[str],
        name: str,
        **kwargs: Any,
    ):
        """
        Initializes the BaseChartClass with the given features, labels, and name.

        Args:
            features (ee.FeatureCollection | pd.DataFrame): The features to plot.
            default_labels (List[str]): The default labels for the chart.
            name (str): The name of the chart.
            **kwargs: Additional keyword arguments to set as attributes.
        """
        self.ylim = None
        self.xlim = None
        self.title = ""
        self.legend_location = "top-left"
        self.layout_width = None
        self.layout_height = None
        self.display_legend = True
        self.x_label = None
        self.y_label = None
        self.labels = default_labels
        self.width = None
        self.height = None
        self.name = name

        if isinstance(self.labels, list) and (len(self.labels) > 1):
            self.colors = [
                "#604791",
                "#1d6b99",
                "#39a8a7",
                "#0f8755",
                "#76b349",
                "#f0af07",
                "#e37d05",
                "#cf513e",
                "#96356f",
                "#724173",
                "#9c4f97",
                "#696969",
            ]
        else:
            self.colors = "black"

        if isinstance(features, ee.FeatureCollection):
            self.df = ee_to_df(features)
        elif isinstance(features, pd.DataFrame):
            self.df = features

        for key, value in kwargs.items():
            setattr(self, key, value)

    @classmethod
    def get_data(cls) -> None:
        """
        Placeholder method to get data for the chart.
        """
        pass

    @classmethod
    def plot_chart(cls) -> None:
        """
        Placeholder method to plot the chart.
        """
        pass

    def __repr__(self) -> str:
        """
        Returns the string representation of the chart.

        Returns:
            str: The name of the chart.
        """
        return self.name

__init__(features, default_labels, name, **kwargs)

Initializes the BaseChartClass with the given features, labels, and name.

Parameters:

Name Type Description Default
features FeatureCollection | DataFrame

The features to plot.

required
default_labels List[str]

The default labels for the chart.

required
name str

The name of the chart.

required
**kwargs Any

Additional keyword arguments to set as attributes.

{}
Source code in geemap/chart.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def __init__(
    self,
    features: Union[ee.FeatureCollection, pd.DataFrame],
    default_labels: List[str],
    name: str,
    **kwargs: Any,
):
    """
    Initializes the BaseChartClass with the given features, labels, and name.

    Args:
        features (ee.FeatureCollection | pd.DataFrame): The features to plot.
        default_labels (List[str]): The default labels for the chart.
        name (str): The name of the chart.
        **kwargs: Additional keyword arguments to set as attributes.
    """
    self.ylim = None
    self.xlim = None
    self.title = ""
    self.legend_location = "top-left"
    self.layout_width = None
    self.layout_height = None
    self.display_legend = True
    self.x_label = None
    self.y_label = None
    self.labels = default_labels
    self.width = None
    self.height = None
    self.name = name

    if isinstance(self.labels, list) and (len(self.labels) > 1):
        self.colors = [
            "#604791",
            "#1d6b99",
            "#39a8a7",
            "#0f8755",
            "#76b349",
            "#f0af07",
            "#e37d05",
            "#cf513e",
            "#96356f",
            "#724173",
            "#9c4f97",
            "#696969",
        ]
    else:
        self.colors = "black"

    if isinstance(features, ee.FeatureCollection):
        self.df = ee_to_df(features)
    elif isinstance(features, pd.DataFrame):
        self.df = features

    for key, value in kwargs.items():
        setattr(self, key, value)

__repr__()

Returns the string representation of the chart.

Returns:

Name Type Description
str str

The name of the chart.

Source code in geemap/chart.py
577
578
579
580
581
582
583
584
def __repr__(self) -> str:
    """
    Returns the string representation of the chart.

    Returns:
        str: The name of the chart.
    """
    return self.name

get_data() classmethod

Placeholder method to get data for the chart.

Source code in geemap/chart.py
563
564
565
566
567
568
@classmethod
def get_data(cls) -> None:
    """
    Placeholder method to get data for the chart.
    """
    pass

plot_chart() classmethod

Placeholder method to plot the chart.

Source code in geemap/chart.py
570
571
572
573
574
575
@classmethod
def plot_chart(cls) -> None:
    """
    Placeholder method to plot the chart.
    """
    pass

Chart

A class to create and display various types of charts from a data table.

Attributes:

Name Type Description
data_table DataFrame

The data to be displayed in the charts.

chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'.

chart

The bqplot Figure object for the chart.

Source code in geemap/chart.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
class Chart:
    """
    A class to create and display various types of charts from a data table.

    Attributes:
        data_table (pd.DataFrame): The data to be displayed in the charts.
        chart_type (str): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart',
            'AreaChart', and 'Table'.
        chart: The bqplot Figure object for the chart.
    """

    def __init__(
        self,
        data_table: Union[Dict[str, List[Any]], pd.DataFrame],
        chart_type: str = "LineChart",
        x_cols: Optional[List[str]] = None,
        y_cols: Optional[List[str]] = None,
        colors: Optional[List[str]] = None,
        title: Optional[str] = None,
        x_label: Optional[str] = None,
        y_label: Optional[str] = None,
        **kwargs: Any,
    ) -> None:
        """
        Initializes the Chart with data.

        Args:
            data_table (Union[Dict[str, List[Any]], pd.DataFrame]): A 2-D array of data.
                If it's a dictionary, it will be converted to a DataFrame.
            chart_type (str): The type of chart to create. Supported types are
                'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
                'PieChart', 'AreaChart', and 'Table'.
            x_cols (Optional[List[str]]): The columns to use for the x-axis.
                Defaults to the first column.
            y_cols (Optional[List[str]]): The columns to use for the y-axis.
                Defaults to the second column.
            colors (Optional[List[str]]): The colors to use for the chart.
                Defaults to a predefined list of colors.
            title (Optional[str]): The title of the chart. Defaults to the
                chart type.
            x_label (Optional[str]): The label for the x-axis. Defaults to an
                empty string.
            y_label (Optional[str]): The label for the y-axis. Defaults to an
                empty string.
            **kwargs: Additional keyword arguments to pass to the bqplot Figure
                or mark objects. For axes_options, see
                https://bqplot.github.io/bqplot/api/axes
        """
        self.data_table = DataTable(data_table)
        self.chart_type = chart_type
        self.chart = None
        self.title = title
        self.x_label = x_label
        self.y_label = y_label
        self.x_cols = x_cols
        self.y_cols = y_cols
        self.colors = colors
        self.xlim = kwargs.pop("xlim", None)
        self.ylim = kwargs.pop("ylim", None)

        if title is not None:
            kwargs["title"] = title
        self.figure = plt.figure(**kwargs)

        if chart_type is not None:
            self.set_chart_type(chart_type, **kwargs)

    def display(self) -> None:
        """
        Display the chart without toolbar.
        """
        self._set_plt_options()
        display(self.figure)

    def save_png(self, filepath: str = "chart.png", scale: float = 1.0) -> None:
        """
        Save the chart as a PNG image.

        Args:
            filepath (str): The path to save the PNG image. Defaults to 'chart.png'.
            scale (float): The scale factor for the image. Defaults to 1.0.
        """
        self.figure.save_png(filepath, scale=scale)

    def _ipython_display_(self) -> None:
        """
        Display the chart with toolbar.
        """
        self._set_plt_options()
        plt.show()

    def _set_plt_options(self) -> None:
        """
        Set the title and labels for the chart.
        """
        if self.title is not None:
            self.figure.title = self.title
        if self.x_label is not None:
            plt.xlabel(self.x_label)
        if self.y_label is not None:
            plt.ylabel(self.y_label)
        if self.xlim is not None:
            plt.xlim(self.xlim[0], self.xlim[1])
        if self.ylim is not None:
            plt.ylim(self.ylim[0], self.ylim[1])

    def set_chart_type(
        self,
        chart_type: str,
        clear: bool = True,
        **kwargs: Any,
    ) -> None:
        """
        Sets the chart type and other chart properties.

        Args:
            chart_type (str): The type of chart to create. Supported types are
                'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
                'PieChart', 'AreaChart', and 'Table'.
            clear (bool): Whether to clear the current chart before setting a new one.
                Defaults to True.
            **kwargs: Additional keyword arguments to pass to the bqplot Figure
                or mark objects.

        Returns:
            Chart: The Chart instance with the chart set.
        """
        if clear:
            plt.clear()
        self.chart_type = chart_type
        x_cols = self.x_cols
        y_cols = self.y_cols
        colors = self.colors

        if x_cols is None:
            x_cols = [self.data_table.columns[0]]
        if y_cols is None:
            y_cols = [self.data_table.columns[1]]

        if isinstance(x_cols, str):
            x_cols = [x_cols]

        if isinstance(y_cols, str):
            y_cols = [y_cols]

        if len(x_cols) == 1 and len(y_cols) > 1:
            x_cols = x_cols * len(y_cols)

        if "axes_options" not in kwargs:
            kwargs["axes_options"] = {
                "x": {"label_offset": "30px"},
                "y": {"label_offset": "40px"},
            }

        if chart_type == "PieChart":
            if colors is None:
                colors = [
                    "#1f77b4",
                    "#ff7f0e",
                    "#2ca02c",
                    "#d62728",
                    "#9467bd",
                    "#8c564b",
                    "#e377c2",
                    "#7f7f7f",
                    "#bcbd22",
                    "#17becf",
                ]  # Default pie chart colors
        else:
            if colors is None:
                colors = [
                    "blue",
                    "orange",
                    "green",
                    "red",
                    "purple",
                    "brown",
                ]  # Default colors

        if chart_type == "IntervalChart":

            x = self.data_table[x_cols[0]]
            y = [self.data_table[y_col] for y_col in y_cols]
            if "fill" not in kwargs:
                kwargs["fill"] = "between"

            self.chart = plt.plot(
                x,
                y,
                colors=colors,
                **kwargs,
            )
        else:
            for i, (x_col, y_col) in enumerate(zip(x_cols, y_cols)):
                color = colors[i % len(colors)]
                if "display_legend" not in kwargs and len(y_cols) > 1:
                    kwargs["display_legend"] = True
                    kwargs["labels"] = [y_col]
                else:
                    kwargs["labels"] = [y_col]

                x = self.data_table[x_col]
                y = self.data_table[y_col]

                if isinstance(x, pd.Series) and (
                    not pd.api.types.is_datetime64_any_dtype(x)
                ):
                    x = x.tolist()
                if isinstance(y, pd.Series) and (
                    not pd.api.types.is_datetime64_any_dtype(y)
                ):
                    y = y.tolist()

                if chart_type == "ScatterChart":
                    self.chart = plt.scatter(
                        x,
                        y,
                        colors=[color],
                        **kwargs,
                    )
                elif chart_type == "LineChart":
                    self.chart = plt.plot(
                        x,
                        y,
                        colors=[color],
                        **kwargs,
                    )
                elif chart_type == "AreaChart":
                    if "fill" not in kwargs:
                        kwargs["fill"] = "bottom"
                    self.chart = plt.plot(
                        x,
                        y,
                        colors=[color],
                        **kwargs,
                    )
                elif chart_type == "ColumnChart":
                    self.chart = plt.bar(
                        x,
                        y,
                        colors=[color],
                        **kwargs,
                    )
                elif chart_type == "BarChart":
                    if "orientation" not in kwargs:
                        kwargs["orientation"] = "horizontal"
                    self.chart = plt.bar(
                        x,
                        y,
                        colors=[color],
                        **kwargs,
                    )
                elif chart_type == "AreaChart":
                    if "fill" not in kwargs:
                        kwargs["fill"] = "bottom"
                    self.chart = plt.plot(
                        x,
                        y,
                        colors=[color],
                        **kwargs,
                    )
                elif chart_type == "PieChart":
                    kwargs.pop("labels", None)
                    self.chart = plt.pie(
                        sizes=y,
                        labels=x,
                        colors=colors[: len(x)],
                        **kwargs,
                    )
                elif chart_type == "Table":
                    output = widgets.Output(**kwargs)
                    with output:
                        display(self.data_table)
                    output.layout = widgets.Layout(width="50%")
                    display(output)
                else:
                    self.chart = plt.plot(
                        x,
                        y,
                        colors=[color],
                        **kwargs,
                    )

        self._set_plt_options()

    def get_chart_type(self) -> Optional[str]:
        """
        Get the current chart type.

        Returns:
            Optional[str]: The current chart type, or None if no chart type is set.
        """
        return self.chart_type

    def get_data_table(self) -> DataTable:
        """
        Get the DataTable used by the chart.

        Returns:
            DataTable: The DataTable instance containing the chart data.
        """
        return self.data_table

    def set_data_table(self, data: Union[Dict[str, List[Any]], pd.DataFrame]) -> None:
        """
        Set a new DataTable for the chart.

        Args:
            data (Union[Dict[str, List[Any]], pd.DataFrame]): The new data to be
            used for the chart.
        """
        self.data_table = DataTable(data)

    def set_options(self, **options: Any) -> None:
        """
        Set additional options for the chart.

        Args:
            **options: Additional options to set for the chart.
        """
        for key, value in options.items():
            setattr(self.figure, key, value)

__init__(data_table, chart_type='LineChart', x_cols=None, y_cols=None, colors=None, title=None, x_label=None, y_label=None, **kwargs)

Initializes the Chart with data.

Parameters:

Name Type Description Default
data_table Union[Dict[str, List[Any]], DataFrame]

A 2-D array of data. If it's a dictionary, it will be converted to a DataFrame.

required
chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'.

'LineChart'
x_cols Optional[List[str]]

The columns to use for the x-axis. Defaults to the first column.

None
y_cols Optional[List[str]]

The columns to use for the y-axis. Defaults to the second column.

None
colors Optional[List[str]]

The colors to use for the chart. Defaults to a predefined list of colors.

None
title Optional[str]

The title of the chart. Defaults to the chart type.

None
x_label Optional[str]

The label for the x-axis. Defaults to an empty string.

None
y_label Optional[str]

The label for the y-axis. Defaults to an empty string.

None
**kwargs Any

Additional keyword arguments to pass to the bqplot Figure or mark objects. For axes_options, see https://bqplot.github.io/bqplot/api/axes

{}
Source code in geemap/chart.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def __init__(
    self,
    data_table: Union[Dict[str, List[Any]], pd.DataFrame],
    chart_type: str = "LineChart",
    x_cols: Optional[List[str]] = None,
    y_cols: Optional[List[str]] = None,
    colors: Optional[List[str]] = None,
    title: Optional[str] = None,
    x_label: Optional[str] = None,
    y_label: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """
    Initializes the Chart with data.

    Args:
        data_table (Union[Dict[str, List[Any]], pd.DataFrame]): A 2-D array of data.
            If it's a dictionary, it will be converted to a DataFrame.
        chart_type (str): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
            'PieChart', 'AreaChart', and 'Table'.
        x_cols (Optional[List[str]]): The columns to use for the x-axis.
            Defaults to the first column.
        y_cols (Optional[List[str]]): The columns to use for the y-axis.
            Defaults to the second column.
        colors (Optional[List[str]]): The colors to use for the chart.
            Defaults to a predefined list of colors.
        title (Optional[str]): The title of the chart. Defaults to the
            chart type.
        x_label (Optional[str]): The label for the x-axis. Defaults to an
            empty string.
        y_label (Optional[str]): The label for the y-axis. Defaults to an
            empty string.
        **kwargs: Additional keyword arguments to pass to the bqplot Figure
            or mark objects. For axes_options, see
            https://bqplot.github.io/bqplot/api/axes
    """
    self.data_table = DataTable(data_table)
    self.chart_type = chart_type
    self.chart = None
    self.title = title
    self.x_label = x_label
    self.y_label = y_label
    self.x_cols = x_cols
    self.y_cols = y_cols
    self.colors = colors
    self.xlim = kwargs.pop("xlim", None)
    self.ylim = kwargs.pop("ylim", None)

    if title is not None:
        kwargs["title"] = title
    self.figure = plt.figure(**kwargs)

    if chart_type is not None:
        self.set_chart_type(chart_type, **kwargs)

display()

Display the chart without toolbar.

Source code in geemap/chart.py
247
248
249
250
251
252
def display(self) -> None:
    """
    Display the chart without toolbar.
    """
    self._set_plt_options()
    display(self.figure)

get_chart_type()

Get the current chart type.

Returns:

Type Description
Optional[str]

Optional[str]: The current chart type, or None if no chart type is set.

Source code in geemap/chart.py
465
466
467
468
469
470
471
472
def get_chart_type(self) -> Optional[str]:
    """
    Get the current chart type.

    Returns:
        Optional[str]: The current chart type, or None if no chart type is set.
    """
    return self.chart_type

get_data_table()

Get the DataTable used by the chart.

Returns:

Name Type Description
DataTable DataTable

The DataTable instance containing the chart data.

Source code in geemap/chart.py
474
475
476
477
478
479
480
481
def get_data_table(self) -> DataTable:
    """
    Get the DataTable used by the chart.

    Returns:
        DataTable: The DataTable instance containing the chart data.
    """
    return self.data_table

save_png(filepath='chart.png', scale=1.0)

Save the chart as a PNG image.

Parameters:

Name Type Description Default
filepath str

The path to save the PNG image. Defaults to 'chart.png'.

'chart.png'
scale float

The scale factor for the image. Defaults to 1.0.

1.0
Source code in geemap/chart.py
254
255
256
257
258
259
260
261
262
def save_png(self, filepath: str = "chart.png", scale: float = 1.0) -> None:
    """
    Save the chart as a PNG image.

    Args:
        filepath (str): The path to save the PNG image. Defaults to 'chart.png'.
        scale (float): The scale factor for the image. Defaults to 1.0.
    """
    self.figure.save_png(filepath, scale=scale)

set_chart_type(chart_type, clear=True, **kwargs)

Sets the chart type and other chart properties.

Parameters:

Name Type Description Default
chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'.

required
clear bool

Whether to clear the current chart before setting a new one. Defaults to True.

True
**kwargs Any

Additional keyword arguments to pass to the bqplot Figure or mark objects.

{}

Returns:

Name Type Description
Chart None

The Chart instance with the chart set.

Source code in geemap/chart.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
def set_chart_type(
    self,
    chart_type: str,
    clear: bool = True,
    **kwargs: Any,
) -> None:
    """
    Sets the chart type and other chart properties.

    Args:
        chart_type (str): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
            'PieChart', 'AreaChart', and 'Table'.
        clear (bool): Whether to clear the current chart before setting a new one.
            Defaults to True.
        **kwargs: Additional keyword arguments to pass to the bqplot Figure
            or mark objects.

    Returns:
        Chart: The Chart instance with the chart set.
    """
    if clear:
        plt.clear()
    self.chart_type = chart_type
    x_cols = self.x_cols
    y_cols = self.y_cols
    colors = self.colors

    if x_cols is None:
        x_cols = [self.data_table.columns[0]]
    if y_cols is None:
        y_cols = [self.data_table.columns[1]]

    if isinstance(x_cols, str):
        x_cols = [x_cols]

    if isinstance(y_cols, str):
        y_cols = [y_cols]

    if len(x_cols) == 1 and len(y_cols) > 1:
        x_cols = x_cols * len(y_cols)

    if "axes_options" not in kwargs:
        kwargs["axes_options"] = {
            "x": {"label_offset": "30px"},
            "y": {"label_offset": "40px"},
        }

    if chart_type == "PieChart":
        if colors is None:
            colors = [
                "#1f77b4",
                "#ff7f0e",
                "#2ca02c",
                "#d62728",
                "#9467bd",
                "#8c564b",
                "#e377c2",
                "#7f7f7f",
                "#bcbd22",
                "#17becf",
            ]  # Default pie chart colors
    else:
        if colors is None:
            colors = [
                "blue",
                "orange",
                "green",
                "red",
                "purple",
                "brown",
            ]  # Default colors

    if chart_type == "IntervalChart":

        x = self.data_table[x_cols[0]]
        y = [self.data_table[y_col] for y_col in y_cols]
        if "fill" not in kwargs:
            kwargs["fill"] = "between"

        self.chart = plt.plot(
            x,
            y,
            colors=colors,
            **kwargs,
        )
    else:
        for i, (x_col, y_col) in enumerate(zip(x_cols, y_cols)):
            color = colors[i % len(colors)]
            if "display_legend" not in kwargs and len(y_cols) > 1:
                kwargs["display_legend"] = True
                kwargs["labels"] = [y_col]
            else:
                kwargs["labels"] = [y_col]

            x = self.data_table[x_col]
            y = self.data_table[y_col]

            if isinstance(x, pd.Series) and (
                not pd.api.types.is_datetime64_any_dtype(x)
            ):
                x = x.tolist()
            if isinstance(y, pd.Series) and (
                not pd.api.types.is_datetime64_any_dtype(y)
            ):
                y = y.tolist()

            if chart_type == "ScatterChart":
                self.chart = plt.scatter(
                    x,
                    y,
                    colors=[color],
                    **kwargs,
                )
            elif chart_type == "LineChart":
                self.chart = plt.plot(
                    x,
                    y,
                    colors=[color],
                    **kwargs,
                )
            elif chart_type == "AreaChart":
                if "fill" not in kwargs:
                    kwargs["fill"] = "bottom"
                self.chart = plt.plot(
                    x,
                    y,
                    colors=[color],
                    **kwargs,
                )
            elif chart_type == "ColumnChart":
                self.chart = plt.bar(
                    x,
                    y,
                    colors=[color],
                    **kwargs,
                )
            elif chart_type == "BarChart":
                if "orientation" not in kwargs:
                    kwargs["orientation"] = "horizontal"
                self.chart = plt.bar(
                    x,
                    y,
                    colors=[color],
                    **kwargs,
                )
            elif chart_type == "AreaChart":
                if "fill" not in kwargs:
                    kwargs["fill"] = "bottom"
                self.chart = plt.plot(
                    x,
                    y,
                    colors=[color],
                    **kwargs,
                )
            elif chart_type == "PieChart":
                kwargs.pop("labels", None)
                self.chart = plt.pie(
                    sizes=y,
                    labels=x,
                    colors=colors[: len(x)],
                    **kwargs,
                )
            elif chart_type == "Table":
                output = widgets.Output(**kwargs)
                with output:
                    display(self.data_table)
                output.layout = widgets.Layout(width="50%")
                display(output)
            else:
                self.chart = plt.plot(
                    x,
                    y,
                    colors=[color],
                    **kwargs,
                )

    self._set_plt_options()

set_data_table(data)

Set a new DataTable for the chart.

Parameters:

Name Type Description Default
data Union[Dict[str, List[Any]], DataFrame]

The new data to be

required
Source code in geemap/chart.py
483
484
485
486
487
488
489
490
491
def set_data_table(self, data: Union[Dict[str, List[Any]], pd.DataFrame]) -> None:
    """
    Set a new DataTable for the chart.

    Args:
        data (Union[Dict[str, List[Any]], pd.DataFrame]): The new data to be
        used for the chart.
    """
    self.data_table = DataTable(data)

set_options(**options)

Set additional options for the chart.

Parameters:

Name Type Description Default
**options Any

Additional options to set for the chart.

{}
Source code in geemap/chart.py
493
494
495
496
497
498
499
500
501
def set_options(self, **options: Any) -> None:
    """
    Set additional options for the chart.

    Args:
        **options: Additional options to set for the chart.
    """
    for key, value in options.items():
        setattr(self.figure, key, value)

DataTable

Bases: DataFrame

Source code in geemap/chart.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class DataTable(pd.DataFrame):

    def __init__(
        self,
        data: Union[Dict[str, List[Any]], pd.DataFrame, None] = None,
        date_column: Optional[str] = None,
        date_format: Optional[str] = None,
        **kwargs: Any,
    ) -> None:
        """
        Initializes the DataTable with data.

        Args:
            data (Union[Dict[str, List[Any]], pd.DataFrame, None]): The input
                data. If it's a dictionary, it will be converted to a DataFrame.
            date_column (Optional[str]): The date column to convert to a DataFrame.
            date_format (Optional[str]): The format of the date column.
            **kwargs: Additional keyword arguments to pass to the pd.DataFrame
                constructor.
        """
        if isinstance(data, ee.FeatureCollection):
            data = ee_to_df(data)
        elif isinstance(data, ee.List):
            data = data.getInfo()
            kwargs["columns"] = data[0]
            data = data[1:]

        super().__init__(data, **kwargs)

        if date_column is not None:
            self[date_column] = pd.to_datetime(
                self[date_column], format=date_format, errors="coerce"
            )

__init__(data=None, date_column=None, date_format=None, **kwargs)

Initializes the DataTable with data.

Parameters:

Name Type Description Default
data Union[Dict[str, List[Any]], DataFrame, None]

The input data. If it's a dictionary, it will be converted to a DataFrame.

None
date_column Optional[str]

The date column to convert to a DataFrame.

None
date_format Optional[str]

The format of the date column.

None
**kwargs Any

Additional keyword arguments to pass to the pd.DataFrame constructor.

{}
Source code in geemap/chart.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def __init__(
    self,
    data: Union[Dict[str, List[Any]], pd.DataFrame, None] = None,
    date_column: Optional[str] = None,
    date_format: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """
    Initializes the DataTable with data.

    Args:
        data (Union[Dict[str, List[Any]], pd.DataFrame, None]): The input
            data. If it's a dictionary, it will be converted to a DataFrame.
        date_column (Optional[str]): The date column to convert to a DataFrame.
        date_format (Optional[str]): The format of the date column.
        **kwargs: Additional keyword arguments to pass to the pd.DataFrame
            constructor.
    """
    if isinstance(data, ee.FeatureCollection):
        data = ee_to_df(data)
    elif isinstance(data, ee.List):
        data = data.getInfo()
        kwargs["columns"] = data[0]
        data = data[1:]

    super().__init__(data, **kwargs)

    if date_column is not None:
        self[date_column] = pd.to_datetime(
            self[date_column], format=date_format, errors="coerce"
        )

Feature_ByFeature

Bases: BarChart

An object to define variables and get_data method for features by feature.

Source code in geemap/chart.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
class Feature_ByFeature(BarChart):
    """An object to define variables and get_data method for features by feature."""

    def __init__(
        self,
        features: Union[ee.FeatureCollection, pd.DataFrame],
        x_property: str,
        y_properties: List[str],
        name: str = "feature.byFeature",
        **kwargs: Any,
    ):
        """
        Initializes the Feature_ByFeature with the given features, x_property,
        y_properties, and name.

        Args:
            features (ee.FeatureCollection | pd.DataFrame): The features to plot.
            x_property (str): The property to use for the x-axis.
            y_properties (List[str]): The properties to use for the y-axis.
            name (str, optional): The name of the chart. Defaults to
                'feature.byFeature'.
            **kwargs: Additional keyword arguments to set as attributes.
        """
        default_labels = y_properties
        super().__init__(features, default_labels, name, **kwargs)
        self.x_data, self.y_data = self.get_data(x_property, y_properties)

    def get_data(
        self, x_property: str, y_properties: List[str]
    ) -> Tuple[List[Any], List[Any]]:
        """
        Gets the data for the chart.

        Args:
            x_property (str): The property to use for the x-axis.
            y_properties (List[str]): The properties to use for the y-axis.

        Returns:
            Tuple[List[Any], List[Any]]: The x and y data for the chart.
        """
        x_data = list(self.df[x_property])
        y_data = list(self.df[y_properties].values.T)
        return x_data, y_data

__init__(features, x_property, y_properties, name='feature.byFeature', **kwargs)

Initializes the Feature_ByFeature with the given features, x_property, y_properties, and name.

Parameters:

Name Type Description Default
features FeatureCollection | DataFrame

The features to plot.

required
x_property str

The property to use for the x-axis.

required
y_properties List[str]

The properties to use for the y-axis.

required
name str

The name of the chart. Defaults to 'feature.byFeature'.

'feature.byFeature'
**kwargs Any

Additional keyword arguments to set as attributes.

{}
Source code in geemap/chart.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
def __init__(
    self,
    features: Union[ee.FeatureCollection, pd.DataFrame],
    x_property: str,
    y_properties: List[str],
    name: str = "feature.byFeature",
    **kwargs: Any,
):
    """
    Initializes the Feature_ByFeature with the given features, x_property,
    y_properties, and name.

    Args:
        features (ee.FeatureCollection | pd.DataFrame): The features to plot.
        x_property (str): The property to use for the x-axis.
        y_properties (List[str]): The properties to use for the y-axis.
        name (str, optional): The name of the chart. Defaults to
            'feature.byFeature'.
        **kwargs: Additional keyword arguments to set as attributes.
    """
    default_labels = y_properties
    super().__init__(features, default_labels, name, **kwargs)
    self.x_data, self.y_data = self.get_data(x_property, y_properties)

get_data(x_property, y_properties)

Gets the data for the chart.

Parameters:

Name Type Description Default
x_property str

The property to use for the x-axis.

required
y_properties List[str]

The properties to use for the y-axis.

required

Returns:

Type Description
Tuple[List[Any], List[Any]]

Tuple[List[Any], List[Any]]: The x and y data for the chart.

Source code in geemap/chart.py
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
def get_data(
    self, x_property: str, y_properties: List[str]
) -> Tuple[List[Any], List[Any]]:
    """
    Gets the data for the chart.

    Args:
        x_property (str): The property to use for the x-axis.
        y_properties (List[str]): The properties to use for the y-axis.

    Returns:
        Tuple[List[Any], List[Any]]: The x and y data for the chart.
    """
    x_data = list(self.df[x_property])
    y_data = list(self.df[y_properties].values.T)
    return x_data, y_data

Feature_ByProperty

Bases: BarChart

An object to define variables and get_data method for features by property.

Source code in geemap/chart.py
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
class Feature_ByProperty(BarChart):
    """An object to define variables and get_data method for features by property."""

    def __init__(
        self,
        features: Union[ee.FeatureCollection, pd.DataFrame],
        x_properties: Union[List[str], Dict[str, str]],
        series_property: str,
        name: str = "feature.byProperty",
        **kwargs: Any,
    ):
        """
        Initializes the Feature_ByProperty with the given features, x_properties,
        series_property, and name.

        Args:
            features (ee.FeatureCollection | pd.DataFrame): The features to plot.
            x_properties (List[str] | Dict[str, str]): The properties to use for
                the x-axis.
            series_property (str): The property to use for labeling the series.
            name (str, optional): The name of the chart. Defaults to
                'feature.byProperty'.
            **kwargs: Additional keyword arguments to set as attributes.

        Raises:
            Exception: If 'labels' is in kwargs.
        """
        default_labels = None
        super().__init__(features, default_labels, name, **kwargs)
        if "labels" in kwargs:
            raise Exception("Please remove labels in kwargs and try again.")

        self.labels = list(self.df[series_property])
        self.x_data, self.y_data = self.get_data(x_properties)

    def get_data(
        self, x_properties: Union[List[str], Dict[str, str]]
    ) -> Tuple[List[Any], List[Any]]:
        """
        Gets the data for the chart.

        Args:
            x_properties (List[str] | Dict[str, str]): The properties to use for
                the x-axis.

        Returns:
            Tuple[List[Any], List[Any]]: The x and y data for the chart.

        Raises:
            Exception: If x_properties is not a list or dictionary.
        """
        if isinstance(x_properties, list):
            x_data = x_properties
            y_data = self.df[x_properties].values
        elif isinstance(x_properties, dict):
            x_data = list(x_properties.values())
            y_data = self.df[list(x_properties.keys())].values
        else:
            raise Exception("x_properties must be a list or dictionary.")

        return x_data, y_data

__init__(features, x_properties, series_property, name='feature.byProperty', **kwargs)

Initializes the Feature_ByProperty with the given features, x_properties, series_property, and name.

Parameters:

Name Type Description Default
features FeatureCollection | DataFrame

The features to plot.

required
x_properties List[str] | Dict[str, str]

The properties to use for the x-axis.

required
series_property str

The property to use for labeling the series.

required
name str

The name of the chart. Defaults to 'feature.byProperty'.

'feature.byProperty'
**kwargs Any

Additional keyword arguments to set as attributes.

{}

Raises:

Type Description
Exception

If 'labels' is in kwargs.

Source code in geemap/chart.py
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
def __init__(
    self,
    features: Union[ee.FeatureCollection, pd.DataFrame],
    x_properties: Union[List[str], Dict[str, str]],
    series_property: str,
    name: str = "feature.byProperty",
    **kwargs: Any,
):
    """
    Initializes the Feature_ByProperty with the given features, x_properties,
    series_property, and name.

    Args:
        features (ee.FeatureCollection | pd.DataFrame): The features to plot.
        x_properties (List[str] | Dict[str, str]): The properties to use for
            the x-axis.
        series_property (str): The property to use for labeling the series.
        name (str, optional): The name of the chart. Defaults to
            'feature.byProperty'.
        **kwargs: Additional keyword arguments to set as attributes.

    Raises:
        Exception: If 'labels' is in kwargs.
    """
    default_labels = None
    super().__init__(features, default_labels, name, **kwargs)
    if "labels" in kwargs:
        raise Exception("Please remove labels in kwargs and try again.")

    self.labels = list(self.df[series_property])
    self.x_data, self.y_data = self.get_data(x_properties)

get_data(x_properties)

Gets the data for the chart.

Parameters:

Name Type Description Default
x_properties List[str] | Dict[str, str]

The properties to use for the x-axis.

required

Returns:

Type Description
Tuple[List[Any], List[Any]]

Tuple[List[Any], List[Any]]: The x and y data for the chart.

Raises:

Type Description
Exception

If x_properties is not a list or dictionary.

Source code in geemap/chart.py
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
def get_data(
    self, x_properties: Union[List[str], Dict[str, str]]
) -> Tuple[List[Any], List[Any]]:
    """
    Gets the data for the chart.

    Args:
        x_properties (List[str] | Dict[str, str]): The properties to use for
            the x-axis.

    Returns:
        Tuple[List[Any], List[Any]]: The x and y data for the chart.

    Raises:
        Exception: If x_properties is not a list or dictionary.
    """
    if isinstance(x_properties, list):
        x_data = x_properties
        y_data = self.df[x_properties].values
    elif isinstance(x_properties, dict):
        x_data = list(x_properties.values())
        y_data = self.df[list(x_properties.keys())].values
    else:
        raise Exception("x_properties must be a list or dictionary.")

    return x_data, y_data

Feature_Groups

Bases: BarChart

An object to define variables and get_data method for feature groups.

Source code in geemap/chart.py
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
class Feature_Groups(BarChart):
    """An object to define variables and get_data method for feature groups."""

    def __init__(
        self,
        features: Union[ee.FeatureCollection, pd.DataFrame],
        x_property: str,
        y_property: str,
        series_property: str,
        name: str = "feature.groups",
        type: str = "stacked",
        **kwargs: Any,
    ):
        """
        Initializes the Feature_Groups with the given features, x_property,
        y_property, series_property, name, and type.

        Args:
            features (ee.FeatureCollection | pd.DataFrame): The features to plot.
            x_property (str): The property to use for the x-axis.
            y_property (str): The property to use for the y-axis.
            series_property (str): The property to use for labeling the series.
            name (str, optional): The name of the chart. Defaults to 'feature.groups'.
            type (str, optional): The type of bar chart ('grouped' or 'stacked').
                Defaults to 'stacked'.
            **kwargs: Additional keyword arguments to set as attributes.
        """
        df = ee_to_df(features)
        self.unique_series_values = df[series_property].unique().tolist()
        default_labels = [str(x) for x in self.unique_series_values]
        self.yProperty = y_property
        super().__init__(features, default_labels, name, type, **kwargs)

        self.new_column_names = self.get_column_names(series_property, y_property)
        self.x_data, self.y_data = self.get_data(x_property, self.new_column_names)

    def get_column_names(self, series_property: str, y_property: str) -> List[str]:
        """
        Gets the new column names for the DataFrame.

        Args:
            series_property (str): The property to use for labeling the series.
            y_property (str): The property to use for the y-axis.

        Returns:
            List[str]: The new column names.
        """
        new_column_names = []

        for value in self.unique_series_values:
            sample_filter = (self.df[series_property] == value).map({True: 1, False: 0})
            column_name = str(y_property) + "_" + str(value)
            self.df[column_name] = self.df[y_property] * sample_filter
            new_column_names.append(column_name)

        return new_column_names

    def get_data(
        self, x_property: str, new_column_names: List[str]
    ) -> Tuple[List[Any], List[Any]]:
        """
        Gets the data for the chart.

        Args:
            x_property (str): The property to use for the x-axis.
            new_column_names (List[str]): The new column names for the y-axis.

        Returns:
            Tuple[List[Any], List[Any]]: The x and y data for the chart.
        """
        x_data = list(self.df[x_property])
        y_data = [self.df[x] for x in new_column_names]

        return x_data, y_data

__init__(features, x_property, y_property, series_property, name='feature.groups', type='stacked', **kwargs)

Initializes the Feature_Groups with the given features, x_property, y_property, series_property, name, and type.

Parameters:

Name Type Description Default
features FeatureCollection | DataFrame

The features to plot.

required
x_property str

The property to use for the x-axis.

required
y_property str

The property to use for the y-axis.

required
series_property str

The property to use for labeling the series.

required
name str

The name of the chart. Defaults to 'feature.groups'.

'feature.groups'
type str

The type of bar chart ('grouped' or 'stacked'). Defaults to 'stacked'.

'stacked'
**kwargs Any

Additional keyword arguments to set as attributes.

{}
Source code in geemap/chart.py
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
def __init__(
    self,
    features: Union[ee.FeatureCollection, pd.DataFrame],
    x_property: str,
    y_property: str,
    series_property: str,
    name: str = "feature.groups",
    type: str = "stacked",
    **kwargs: Any,
):
    """
    Initializes the Feature_Groups with the given features, x_property,
    y_property, series_property, name, and type.

    Args:
        features (ee.FeatureCollection | pd.DataFrame): The features to plot.
        x_property (str): The property to use for the x-axis.
        y_property (str): The property to use for the y-axis.
        series_property (str): The property to use for labeling the series.
        name (str, optional): The name of the chart. Defaults to 'feature.groups'.
        type (str, optional): The type of bar chart ('grouped' or 'stacked').
            Defaults to 'stacked'.
        **kwargs: Additional keyword arguments to set as attributes.
    """
    df = ee_to_df(features)
    self.unique_series_values = df[series_property].unique().tolist()
    default_labels = [str(x) for x in self.unique_series_values]
    self.yProperty = y_property
    super().__init__(features, default_labels, name, type, **kwargs)

    self.new_column_names = self.get_column_names(series_property, y_property)
    self.x_data, self.y_data = self.get_data(x_property, self.new_column_names)

get_column_names(series_property, y_property)

Gets the new column names for the DataFrame.

Parameters:

Name Type Description Default
series_property str

The property to use for labeling the series.

required
y_property str

The property to use for the y-axis.

required

Returns:

Type Description
List[str]

List[str]: The new column names.

Source code in geemap/chart.py
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
def get_column_names(self, series_property: str, y_property: str) -> List[str]:
    """
    Gets the new column names for the DataFrame.

    Args:
        series_property (str): The property to use for labeling the series.
        y_property (str): The property to use for the y-axis.

    Returns:
        List[str]: The new column names.
    """
    new_column_names = []

    for value in self.unique_series_values:
        sample_filter = (self.df[series_property] == value).map({True: 1, False: 0})
        column_name = str(y_property) + "_" + str(value)
        self.df[column_name] = self.df[y_property] * sample_filter
        new_column_names.append(column_name)

    return new_column_names

get_data(x_property, new_column_names)

Gets the data for the chart.

Parameters:

Name Type Description Default
x_property str

The property to use for the x-axis.

required
new_column_names List[str]

The new column names for the y-axis.

required

Returns:

Type Description
Tuple[List[Any], List[Any]]

Tuple[List[Any], List[Any]]: The x and y data for the chart.

Source code in geemap/chart.py
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def get_data(
    self, x_property: str, new_column_names: List[str]
) -> Tuple[List[Any], List[Any]]:
    """
    Gets the data for the chart.

    Args:
        x_property (str): The property to use for the x-axis.
        new_column_names (List[str]): The new column names for the y-axis.

    Returns:
        Tuple[List[Any], List[Any]]: The x and y data for the chart.
    """
    x_data = list(self.df[x_property])
    y_data = [self.df[x] for x in new_column_names]

    return x_data, y_data

LineChart

Bases: BarChart

A class to define variables and get_data method for a line chart.

Source code in geemap/chart.py
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
class LineChart(BarChart):
    """A class to define variables and get_data method for a line chart."""

    def __init__(
        self,
        features: Union[ee.FeatureCollection, pd.DataFrame],
        labels: List[str],
        name: str = "line.chart",
        **kwargs: Any,
    ):
        """
        Initializes the LineChart with the given features, labels, and name.

        Args:
            features (ee.FeatureCollection | pd.DataFrame): The features to plot.
            labels (List[str]): The labels for the chart.
            name (str, optional): The name of the chart. Defaults to 'line.chart'.
            **kwargs: Additional keyword arguments to set as attributes.
        """
        super().__init__(features, labels, name, **kwargs)

    def plot_chart(self) -> None:
        """
        Plots the line chart.
        """
        fig = plt.figure(
            title=self.title,
            legend_location=self.legend_location,
        )

        self.line_chart = plt.plot(
            self.x_data,
            self.y_data,
            label=self.labels,
        )

        self.generate_tooltip()
        plt.ylim(*self.get_ylim())
        if self.x_label:
            plt.xlabel(self.x_label)
        if self.y_label:
            plt.ylabel(self.y_label)

        if self.width:
            fig.layout.width = self.width
        if self.height:
            fig.layout.height = self.height

        plt.show()

__init__(features, labels, name='line.chart', **kwargs)

Initializes the LineChart with the given features, labels, and name.

Parameters:

Name Type Description Default
features FeatureCollection | DataFrame

The features to plot.

required
labels List[str]

The labels for the chart.

required
name str

The name of the chart. Defaults to 'line.chart'.

'line.chart'
**kwargs Any

Additional keyword arguments to set as attributes.

{}
Source code in geemap/chart.py
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def __init__(
    self,
    features: Union[ee.FeatureCollection, pd.DataFrame],
    labels: List[str],
    name: str = "line.chart",
    **kwargs: Any,
):
    """
    Initializes the LineChart with the given features, labels, and name.

    Args:
        features (ee.FeatureCollection | pd.DataFrame): The features to plot.
        labels (List[str]): The labels for the chart.
        name (str, optional): The name of the chart. Defaults to 'line.chart'.
        **kwargs: Additional keyword arguments to set as attributes.
    """
    super().__init__(features, labels, name, **kwargs)

plot_chart()

Plots the line chart.

Source code in geemap/chart.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
def plot_chart(self) -> None:
    """
    Plots the line chart.
    """
    fig = plt.figure(
        title=self.title,
        legend_location=self.legend_location,
    )

    self.line_chart = plt.plot(
        self.x_data,
        self.y_data,
        label=self.labels,
    )

    self.generate_tooltip()
    plt.ylim(*self.get_ylim())
    if self.x_label:
        plt.xlabel(self.x_label)
    if self.y_label:
        plt.ylabel(self.y_label)

    if self.width:
        fig.layout.width = self.width
    if self.height:
        fig.layout.height = self.height

    plt.show()

array_to_df(y_values, x_values=None, y_labels=None, x_label='x', axis=1, **kwargs)

Converts arrays or lists of y-values and optional x-values into a pandas DataFrame.

Parameters:

Name Type Description Default
y_values Union[Array, List, List[List[float]]]

The y-values to convert.

required
x_values Optional[Union[Array, List, List[float]]]

The x-values to convert. Defaults to None.

None
y_labels Optional[List[str]]

The labels for the y-values. Defaults to None.

None
x_label str

The label for the x-values. Defaults to "x".

'x'
axis int

The axis along which to transpose the y-values if needed. Defaults to 1.

1
**kwargs Any

Additional keyword arguments to pass to the pandas DataFrame constructor.

{}

Returns:

Type Description
DataFrame

pd.DataFrame: The resulting DataFrame.

Source code in geemap/chart.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def array_to_df(
    y_values: Union[ee.Array, ee.List, List[List[float]]],
    x_values: Optional[Union[ee.Array, ee.List, List[float]]] = None,
    y_labels: Optional[List[str]] = None,
    x_label: str = "x",
    axis: int = 1,
    **kwargs: Any,
) -> pd.DataFrame:
    """
    Converts arrays or lists of y-values and optional x-values into a pandas DataFrame.

    Args:
        y_values (Union[ee.Array, ee.List, List[List[float]]]): The y-values to convert.
        x_values (Optional[Union[ee.Array, ee.List, List[float]]]): The x-values to convert.
            Defaults to None.
        y_labels (Optional[List[str]]): The labels for the y-values. Defaults to None.
        x_label (str): The label for the x-values. Defaults to "x".
        axis (int): The axis along which to transpose the y-values if needed. Defaults to 1.
        **kwargs: Additional keyword arguments to pass to the pandas DataFrame constructor.

    Returns:
        pd.DataFrame: The resulting DataFrame.
    """

    if isinstance(y_values, ee.Array) or isinstance(y_values, ee.List):
        y_values = y_values.getInfo()

    if isinstance(x_values, ee.Array) or isinstance(x_values, ee.List):
        x_values = x_values.getInfo()

    if axis == 0:
        y_values = np.transpose(y_values)

    if x_values is None:
        x_values = list(range(1, len(y_values[0]) + 1))

    data = {x_label: x_values}

    if not isinstance(y_values[0], list):
        y_values = [y_values]

    if y_labels is None:
        y_labels = [
            f"y{str(i+1).zfill(len(str(len(y_values))))}" for i in range(len(y_values))
        ]

    if len(y_labels) != len(y_values):
        raise ValueError("The length of y_labels must match the length of y_values.")

    for i, series in enumerate(y_labels):
        data[series] = y_values[i]

    df = pd.DataFrame(data, **kwargs)
    return df

array_values(array, x_labels=None, axis=1, series_names=None, chart_type='LineChart', colors=None, title=None, x_label=None, y_label=None, **kwargs)

Converts an array to a DataFrame and generates a chart.

Parameters:

Name Type Description Default
array Union[Array, List, List[List[float]]]

The array to convert.

required
x_labels Optional[Union[Array, List, List[float]]]

The labels for the x-axis. Defaults to None.

None
axis int

The axis along which to transpose the array if needed. Defaults to 1.

1
series_names Optional[List[str]]

The names of the series. Defaults to None.

None
chart_type str

The type of chart to create. Defaults to "LineChart".

'LineChart'
colors Optional[List[str]]

The colors to use for the chart. Defaults to None.

None
title Optional[str]

The title of the chart. Defaults to None.

None
x_label Optional[str]

The label for the x-axis. Defaults to None.

None
y_label Optional[str]

The label for the y-axis. Defaults to None.

None
**kwargs Any

Additional keyword arguments to pass to the Chart constructor.

{}

Returns:

Name Type Description
Chart Chart

The generated chart.

Source code in geemap/chart.py
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
def array_values(
    array: Union[ee.Array, ee.List, List[List[float]]],
    x_labels: Optional[Union[ee.Array, ee.List, List[float]]] = None,
    axis: int = 1,
    series_names: Optional[List[str]] = None,
    chart_type: str = "LineChart",
    colors: Optional[List[str]] = None,
    title: Optional[str] = None,
    x_label: Optional[str] = None,
    y_label: Optional[str] = None,
    **kwargs: Any,
) -> Chart:
    """
    Converts an array to a DataFrame and generates a chart.

    Args:
        array (Union[ee.Array, ee.List, List[List[float]]]): The array to convert.
        x_labels (Optional[Union[ee.Array, ee.List, List[float]]]): The labels
            for the x-axis. Defaults to None.
        axis (int): The axis along which to transpose the array if needed. Defaults to 1.
        series_names (Optional[List[str]]): The names of the series. Defaults to None.
        chart_type (str): The type of chart to create. Defaults to "LineChart".
        colors (Optional[List[str]]): The colors to use for the chart. Defaults to None.
        title (Optional[str]): The title of the chart. Defaults to None.
        x_label (Optional[str]): The label for the x-axis. Defaults to None.
        y_label (Optional[str]): The label for the y-axis. Defaults to None.
        **kwargs: Additional keyword arguments to pass to the Chart constructor.

    Returns:
        Chart: The generated chart.
    """

    df = array_to_df(array, x_values=x_labels, y_labels=series_names, axis=axis)
    fig = Chart(
        df,
        x_cols=["x"],
        y_cols=df.columns.tolist()[1:],
        chart_type=chart_type,
        colors=colors,
        title=title,
        x_label=x_label,
        y_label=y_label,
        **kwargs,
    )
    return fig

doy_series_by_year(image_collection, band_name, region=None, region_reducer=None, scale=None, same_day_reducer=None, start_day=1, end_day=366, chart_type='LineChart', colors=None, title=None, x_label=None, y_label=None, **kwargs)

Generates a time series chart of an image collection for a specific region over multiple years.

Parameters:

Name Type Description Default
image_collection ImageCollection

The image collection to analyze.

required
band_name str

The name of the band to analyze.

required
region Optional[Union[Geometry, FeatureCollection]]

The region to analyze.

None
region_reducer Optional[Union[str, Reducer]]

The reducer type for zonal statistics.

None
scale Optional[int]

The scale in meters at which to perform the analysis.

None
same_day_reducer Optional[Union[str, Reducer]]

The reducer type for daily statistics.

None
start_day int

The start day of the year.

1
end_day int

The end day of the year.

366
chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'.

'LineChart'
colors Optional[List[str]]

The colors to use for the chart. Defaults to a predefined list of colors.

None
title Optional[str]

The title of the chart. Defaults to the chart type.

None
x_label Optional[str]

The label for the x-axis. Defaults to an empty string.

None
y_label Optional[str]

The label for the y-axis. Defaults to an empty string.

None
**kwargs Any

Additional keyword arguments to pass to the bqplot Figure or mark objects. For axes_options, see https://bqplot.github.io/bqplot/api/axes

{}

Returns:

Name Type Description
Chart Chart

The generated chart.

Source code in geemap/chart.py
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
def doy_series_by_year(
    image_collection: ee.ImageCollection,
    band_name: str,
    region: Optional[Union[ee.Geometry, ee.FeatureCollection]] = None,
    region_reducer: Optional[Union[str, ee.Reducer]] = None,
    scale: Optional[int] = None,
    same_day_reducer: Optional[Union[str, ee.Reducer]] = None,
    start_day: int = 1,
    end_day: int = 366,
    chart_type: str = "LineChart",
    colors: Optional[List[str]] = None,
    title: Optional[str] = None,
    x_label: Optional[str] = None,
    y_label: Optional[str] = None,
    **kwargs: Any,
) -> Chart:
    """
    Generates a time series chart of an image collection for a specific region
    over multiple years.

    Args:
        image_collection (ee.ImageCollection): The image collection to analyze.
        band_name (str): The name of the band to analyze.
        region (Optional[Union[ee.Geometry, ee.FeatureCollection]]): The region
            to analyze.
        region_reducer (Optional[Union[str, ee.Reducer]]): The reducer type for
            zonal statistics.
        scale (Optional[int]): The scale in meters at which to perform the analysis.
        same_day_reducer (Optional[Union[str, ee.Reducer]]): The reducer type
            for daily statistics.
        start_day (int): The start day of the year.
        end_day (int): The end day of the year.
        chart_type (str): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
            'PieChart', 'AreaChart', and 'Table'.
        colors (Optional[List[str]]): The colors to use for the chart.
            Defaults to a predefined list of colors.
        title (Optional[str]): The title of the chart. Defaults to the
            chart type.
        x_label (Optional[str]): The label for the x-axis. Defaults to an
            empty string.
        y_label (Optional[str]): The label for the y-axis. Defaults to an
            empty string.
        **kwargs: Additional keyword arguments to pass to the bqplot Figure
            or mark objects. For axes_options, see
            https://bqplot.github.io/bqplot/api/axes

    Returns:
        Chart: The generated chart.
    """

    # Function to add day-of-year ('doy') and year properties to each image.
    def set_doys(collection):
        def add_doy(img):
            date = img.date()
            year = date.get("year")
            doy = date.getRelative("day", "year").floor().add(1)
            return img.set({"doy": doy, "year": year})

        return collection.map(add_doy)

    # Set default values and filters if parameters are not provided.
    region_reducer = region_reducer or ee.Reducer.mean()
    same_day_reducer = same_day_reducer or ee.Reducer.mean()

    # Optionally filter the image collection by region.
    filtered_collection = image_collection
    if region:
        filtered_collection = filtered_collection.filterBounds(region)
    filtered_collection = set_doys(filtered_collection)

    # Filter image collection by day of year.
    filtered_collection = filtered_collection.filter(
        ee.Filter.calendarRange(start_day, end_day, "day_of_year")
    )

    # Generate a feature for each (doy, value, year) combination.
    def create_feature(image):
        value = (
            image.select(band_name)
            .reduceRegion(reducer=region_reducer, geometry=region, scale=scale)
            .get(band_name)
        )  # Get the reduced value for the given band.
        return ee.Feature(
            None, {"doy": image.get("doy"), "year": image.get("year"), "value": value}
        )

    tuples = filtered_collection.map(create_feature)

    # Group by unique (doy, year) pairs.
    distinct_doy_year = tuples.distinct(["doy", "year"])

    # Join the original tuples with the distinct (doy, year) pairs.
    filter = ee.Filter.And(
        ee.Filter.equals(leftField="doy", rightField="doy"),
        ee.Filter.equals(leftField="year", rightField="year"),
    )
    joined = ee.Join.saveAll("matches").apply(
        primary=distinct_doy_year, secondary=tuples, condition=filter
    )

    # For each (doy, year), reduce the values of the joined features.
    def reduce_features(doy_year):
        features = ee.FeatureCollection(ee.List(doy_year.get("matches")))
        value = features.aggregate_array("value").reduce(same_day_reducer)
        return doy_year.set("value", value)

    reduced = joined.map(reduce_features)

    df = ee_to_df(reduced, columns=["doy", "year", "value"])
    df = pivot_df(df, index="doy", columns="year", values="value")
    y_cols = df.columns.tolist()[1:]
    x_cols = "doy"

    fig = Chart(
        df,
        chart_type,
        x_cols,
        y_cols,
        colors,
        title,
        x_label,
        y_label,
        **kwargs,
    )
    return fig

feature_by_feature(features, x_property, y_properties, **kwargs)

Generates a Chart from a set of features. Plots the value of one or more properties for each feature. Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyfeature

Parameters:

Name Type Description Default
features FeatureCollection

The feature collection to generate a chart from.

required
x_property str

Features labeled by x_property.

required
y_properties List[str]

Values of y_properties.

required
**kwargs Any

Additional keyword arguments to set as attributes.

{}

Raises:

Type Description
Exception

Errors when creating the chart.

Source code in geemap/chart.py
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def feature_by_feature(
    features: ee.FeatureCollection,
    x_property: str,
    y_properties: List[str],
    **kwargs: Any,
) -> None:
    """
    Generates a Chart from a set of features. Plots the value of one or more
    properties for each feature.
    Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyfeature

    Args:
        features (ee.FeatureCollection): The feature collection to generate a chart from.
        x_property (str): Features labeled by x_property.
        y_properties (List[str]): Values of y_properties.
        **kwargs: Additional keyword arguments to set as attributes.

    Raises:
        Exception: Errors when creating the chart.
    """
    bar = Feature_ByFeature(
        features=features, x_property=x_property, y_properties=y_properties, **kwargs
    )

    try:
        bar.plot_chart()
    except Exception as e:
        raise Exception(e)

feature_by_property(features, x_properties, series_property, **kwargs)

Generates a Chart from a set of features. Plots property values of one or more features. Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyproperty

Parameters:

Name Type Description Default
features FeatureCollection

The features to include in the chart.

required
x_properties list | dict

One of (1) a list of properties to be plotted on the x-axis; or (2) a (property, label) dictionary specifying labels for properties to be used as values on the x-axis.

required
series_property str

The name of the property used to label each feature in the legend.

required

Raises:

Type Description
Exception

If the provided xProperties is not a list or dict.

Exception

If the chart fails to create.

Source code in geemap/chart.py
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
def feature_by_property(
    features: ee.FeatureCollection,
    x_properties: Union[list, dict],
    series_property: str,
    **kwargs,
):
    """Generates a Chart from a set of features. Plots property values of one or
     more features.
    Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturebyproperty

    Args:
        features (ee.FeatureCollection): The features to include in the chart.
        x_properties (list | dict): One of (1) a list of properties to be
            plotted on the x-axis; or (2) a (property, label) dictionary
            specifying labels for properties to be used as values on the x-axis.
        series_property (str): The name of the property used to label each
            feature in the legend.

    Raises:
        Exception: If the provided xProperties is not a list or dict.
        Exception: If the chart fails to create.
    """
    bar = Feature_ByProperty(
        features=features,
        x_properties=x_properties,
        series_property=series_property,
        **kwargs,
    )

    try:
        bar.plot_chart()

    except Exception as e:
        raise Exception(e)

feature_groups(features, x_property, y_property, series_property, **kwargs)

Generates a Chart from a set of features. Plots the value of one property for each feature.

Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturegroups

Parameters:

Name Type Description Default
features FeatureCollection

The feature collection to make a chart from.

required
x_property str

Features labeled by xProperty.

required
y_property str

Features labeled by yProperty.

required
series_property str

The property used to label each feature in the legend.

required
**kwargs Any

Additional keyword arguments to set as attributes.

{}

Raises:

Type Description
Exception

Errors when creating the chart.

Source code in geemap/chart.py
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
def feature_groups(
    features: ee.FeatureCollection,
    x_property: str,
    y_property: str,
    series_property: str,
    **kwargs: Any,
) -> None:
    """
    Generates a Chart from a set of features.
    Plots the value of one property for each feature.

    Reference:
    https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturegroups

    Args:
        features (ee.FeatureCollection): The feature collection to make a chart from.
        x_property (str): Features labeled by xProperty.
        y_property (str): Features labeled by yProperty.
        series_property (str): The property used to label each feature in the legend.
        **kwargs: Additional keyword arguments to set as attributes.

    Raises:
        Exception: Errors when creating the chart.
    """

    bar = Feature_Groups(
        features=features,
        x_property=x_property,
        y_property=y_property,
        series_property=series_property,
        **kwargs,
    )

    try:
        bar.plot_chart()

    except Exception as e:
        raise Exception(e)

feature_histogram(features, property, max_buckets=None, min_bucket_width=None, show=True, **kwargs)

Generates a Chart from a set of features. Computes and plots a histogram of the given property. - X-axis = Histogram buckets (of property value). - Y-axis = Frequency

Reference: https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturehistogram

Parameters:

Name Type Description Default
features FeatureCollection

The features to include in the chart.

required
property str

The name of the property to generate the histogram for.

required
max_buckets int

The maximum number of buckets (bins) to use when building a histogram; will be rounded up to a power of 2.

None
min_bucket_width float

The minimum histogram bucket width, or null to allow any power of 2.

None
show bool

Whether to show the chart. If not, it will return the bqplot chart object, which can be used to retrieve data for the chart. Defaults to True.

True
**kwargs Any

Additional keyword arguments to set as attributes.

{}

Raises:

Type Description
Exception

If the provided xProperties is not a list or dict.

Exception

If the chart fails to create.

Returns:

Type Description
Optional[Any]

Optional[Any]: The bqplot chart object if show is False, otherwise None.

Source code in geemap/chart.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
def feature_histogram(
    features: ee.FeatureCollection,
    property: str,
    max_buckets: Optional[int] = None,
    min_bucket_width: Optional[float] = None,
    show: bool = True,
    **kwargs: Any,
) -> Optional[Any]:
    """
    Generates a Chart from a set of features.
    Computes and plots a histogram of the given property.
    - X-axis = Histogram buckets (of property value).
    - Y-axis = Frequency

    Reference:
    https://developers.google.com/earth-engine/guides/charts_feature#uichartfeaturehistogram

    Args:
        features (ee.FeatureCollection): The features to include in the chart.
        property (str): The name of the property to generate the histogram for.
        max_buckets (int, optional): The maximum number of buckets (bins) to use
            when building a histogram; will be rounded up to a power of 2.
        min_bucket_width (float, optional): The minimum histogram bucket width,
            or null to allow any power of 2.
        show (bool, optional): Whether to show the chart. If not, it will return
            the bqplot chart object, which can be used to retrieve data for the
            chart. Defaults to True.
        **kwargs: Additional keyword arguments to set as attributes.

    Raises:
        Exception: If the provided xProperties is not a list or dict.
        Exception: If the chart fails to create.

    Returns:
        Optional[Any]: The bqplot chart object if show is False, otherwise None.
    """
    import math

    if not isinstance(features, ee.FeatureCollection):
        raise Exception("features must be an ee.FeatureCollection")

    first = features.first()
    props = first.propertyNames().getInfo()
    if property not in props:
        raise Exception(
            f"property {property} not found. Available properties: {', '.join(props)}"
        )

    def nextPowerOf2(n):
        return pow(2, math.ceil(math.log2(n)))

    def grow_bin(bin_size, ref):
        while bin_size < ref:
            bin_size *= 2
        return bin_size

    try:
        raw_data = pd.to_numeric(
            pd.Series(features.aggregate_array(property).getInfo())
        )
        y_data = raw_data.tolist()

        if "ylim" in kwargs:
            min_value = kwargs["ylim"][0]
            max_value = kwargs["ylim"][1]
        else:
            min_value = raw_data.min()
            max_value = raw_data.max()

        data_range = max_value - min_value

        if not max_buckets:
            initial_bin_size = nextPowerOf2(data_range / pow(2, 8))
            if min_bucket_width:
                if min_bucket_width < initial_bin_size:
                    bin_size = grow_bin(min_bucket_width, initial_bin_size)
                else:
                    bin_size = min_bucket_width
            else:
                bin_size = initial_bin_size
        else:
            initial_bin_size = math.ceil(data_range / nextPowerOf2(max_buckets))
            if min_bucket_width:
                if min_bucket_width < initial_bin_size:
                    bin_size = grow_bin(min_bucket_width, initial_bin_size)
                else:
                    bin_size = min_bucket_width
            else:
                bin_size = initial_bin_size

        start_bins = (math.floor(min_value / bin_size) * bin_size) - (bin_size / 2)
        end_bins = (math.ceil(max_value / bin_size) * bin_size) + (bin_size / 2)

        if start_bins < min_value:
            y_data.append(start_bins)
        else:
            y_data[y_data.index(min_value)] = start_bins
        if end_bins > max_value:
            y_data.append(end_bins)
        else:
            y_data[y_data.index(max_value)] = end_bins

        num_bins = math.floor((end_bins - start_bins) / bin_size)

        if "title" not in kwargs:
            title = ""
        else:
            title = kwargs["title"]

        fig = plt.figure(title=title)

        if "width" in kwargs:
            fig.layout.width = kwargs["width"]
        if "height" in kwargs:
            fig.layout.height = kwargs["height"]

        if "x_label" not in kwargs:
            x_label = ""
        else:
            x_label = kwargs["x_label"]

        if "y_label" not in kwargs:
            y_label = ""
        else:
            y_label = kwargs["y_label"]

        histogram = plt.hist(
            sample=y_data,
            bins=num_bins,
            axes_options={"count": {"label": y_label}, "sample": {"label": x_label}},
        )

        if "colors" in kwargs:
            histogram.colors = kwargs["colors"]
        if "stroke" in kwargs:
            histogram.stroke = kwargs["stroke"]
        else:
            histogram.stroke = "#ffffff00"
        if "stroke_width" in kwargs:
            histogram.stroke_width = kwargs["stroke_width"]
        else:
            histogram.stroke_width = 0

        if ("x_label" in kwargs) and ("y_label" in kwargs):
            histogram.tooltip = Tooltip(
                fields=["midpoint", "count"],
                labels=[kwargs["x_label"], kwargs["y_label"]],
            )
        else:
            histogram.tooltip = Tooltip(fields=["midpoint", "count"])

        if show:
            plt.show()
        else:
            return histogram

    except Exception as e:
        raise Exception(e)

image_by_class(image, class_band, region, reducer='MEAN', scale=None, class_labels=None, x_labels=None, chart_type='LineChart', **kwargs)

Generates a Chart from an image by class. Extracts and plots band values by class.

Parameters:

Name Type Description Default
image Image

Image to extract band values from.

required
class_band str

The band name to use as class labels.

required
region Geometry | FeatureCollection

The region(s) to reduce.

required
reducer str | Reducer

The reducer type for zonal statistics. Can be one of 'mean', 'median', 'sum', 'min', 'max', etc. Defaults to 'MEAN'.

'MEAN'
scale int

The scale in meters at which to perform the analysis.

None
class_labels List[str]

List of class labels.

None
x_labels List[str]

List of x-axis labels.

None
chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'. Defaults to 'LineChart'.

'LineChart'
**kwargs Any

Additional keyword arguments.

{}

Returns:

Name Type Description
Any Any

The generated chart.

Source code in geemap/chart.py
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
def image_by_class(
    image: ee.Image,
    class_band: str,
    region: Union[ee.Geometry, ee.FeatureCollection],
    reducer: Union[str, ee.Reducer] = "MEAN",
    scale: Optional[int] = None,
    class_labels: Optional[List[str]] = None,
    x_labels: Optional[List[str]] = None,
    chart_type: str = "LineChart",
    **kwargs: Any,
) -> Any:
    """
    Generates a Chart from an image by class. Extracts and plots band values by class.

    Args:
        image (ee.Image): Image to extract band values from.
        class_band (str): The band name to use as class labels.
        region (ee.Geometry | ee.FeatureCollection): The region(s) to reduce.
        reducer (str | ee.Reducer, optional): The reducer type for zonal statistics. Can
            be one of 'mean', 'median', 'sum', 'min', 'max', etc. Defaults to 'MEAN'.
        scale (int, optional): The scale in meters at which to perform the analysis.
        class_labels (List[str], optional): List of class labels.
        x_labels (List[str], optional): List of x-axis labels.
        chart_type (str, optional): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart',
            'AreaChart', and 'Table'. Defaults to 'LineChart'.
        **kwargs: Additional keyword arguments.

    Returns:
        Any: The generated chart.
    """
    fc = zonal_stats(
        image, region, stat_type=reducer, scale=scale, verbose=False, return_fc=True
    )
    bands = image.bandNames().getInfo()
    df = ee_to_df(fc)[bands + [class_band]]

    df_transposed = df.set_index(class_band).T

    if x_labels is not None:
        df_transposed["label"] = x_labels
    else:
        df_transposed["label"] = df_transposed.index

    if class_labels is None:
        y_cols = df_transposed.columns.tolist()
        y_cols.remove("label")
    else:
        y_cols = class_labels

    fig = Chart(
        df_transposed, chart_type=chart_type, x_cols="label", y_cols=y_cols, **kwargs
    )
    return fig

image_by_region(image, regions, reducer, scale, x_property, **kwargs)

Generates a Chart from an image. Extracts and plots band values in one or more regions in the image, with each band in a separate series.

Parameters:

Name Type Description Default
image Image

Image to extract band values from.

required
regions FeatureCollection | Geometry

Regions to reduce. Defaults to the image's footprint.

required
reducer str | Reducer

The reducer type for zonal statistics. Can be one of 'mean', 'median', 'sum', 'min', 'max', etc.

required
scale int

The scale in meters at which to perform the analysis.

required
x_property str

The name of the property in the feature collection to use as the x-axis values.

required
**kwargs Any

Additional keyword arguments to be passed to the feature_by_feature function.

{}

Returns:

Type Description
None

None

Source code in geemap/chart.py
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
def image_by_region(
    image: ee.Image,
    regions: Union[ee.FeatureCollection, ee.Geometry],
    reducer: Union[str, ee.Reducer],
    scale: int,
    x_property: str,
    **kwargs: Any,
) -> None:
    """
    Generates a Chart from an image. Extracts and plots band values in one or more
    regions in the image, with each band in a separate series.

    Args:
        image (ee.Image): Image to extract band values from.
        regions (ee.FeatureCollection | ee.Geometry): Regions to reduce.
            Defaults to the image's footprint.
        reducer (str | ee.Reducer): The reducer type for zonal statistics. Can
            be one of 'mean', 'median', 'sum', 'min', 'max', etc.
        scale (int): The scale in meters at which to perform the analysis.
        x_property (str): The name of the property in the feature collection to
            use as the x-axis values.
        **kwargs: Additional keyword arguments to be passed to the
            `feature_by_feature` function.

    Returns:
        None
    """

    fc = zonal_stats(
        image, regions, stat_type=reducer, scale=scale, verbose=False, return_fc=True
    )
    bands = image.bandNames().getInfo()
    df = ee_to_df(fc)[bands + [x_property]]
    feature_by_feature(df, x_property, bands, **kwargs)

image_doy_series(image_collection, region=None, region_reducer=None, scale=None, year_reducer=None, start_day=1, end_day=366, chart_type='LineChart', colors=None, title=None, x_label=None, y_label=None, **kwargs)

Generates a time series chart of an image collection for a specific region over a range of days of the year.

Parameters:

Name Type Description Default
image_collection ImageCollection

The image collection to analyze.

required
region Optional[Union[Geometry, FeatureCollection]]

The region to reduce.

None
region_reducer Optional[Union[str, Reducer]]

The reducer type for zonal statistics.Can be one of 'mean', 'median', 'sum', 'min', 'max', etc.

None
scale Optional[int]

The scale in meters at which to perform the analysis.

None
year_reducer Optional[Union[str, Reducer]]

The reducer type for yearly statistics.

None
start_day int

The start day of the year.

1
end_day int

The end day of the year.

366
chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'.

'LineChart'
colors Optional[List[str]]

The colors to use for the chart. Defaults to a predefined list of colors.

None
title Optional[str]

The title of the chart. Defaults to the chart type.

None
x_label Optional[str]

The label for the x-axis. Defaults to an empty string.

None
y_label Optional[str]

The label for the y-axis. Defaults to an empty string.

None
**kwargs Any

Additional keyword arguments to pass to the bqplot Figure or mark objects. For axes_options, see https://bqplot.github.io/bqplot/api/axes

{}

Returns:

Name Type Description
Chart Chart

The generated chart.

Source code in geemap/chart.py
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
def image_doy_series(
    image_collection: ee.ImageCollection,
    region: Optional[Union[ee.Geometry, ee.FeatureCollection]] = None,
    region_reducer: Optional[Union[str, ee.Reducer]] = None,
    scale: Optional[int] = None,
    year_reducer: Optional[Union[str, ee.Reducer]] = None,
    start_day: int = 1,
    end_day: int = 366,
    chart_type: str = "LineChart",
    colors: Optional[List[str]] = None,
    title: Optional[str] = None,
    x_label: Optional[str] = None,
    y_label: Optional[str] = None,
    **kwargs: Any,
) -> Chart:
    """
    Generates a time series chart of an image collection for a specific region
        over a range of days of the year.

    Args:
        image_collection (ee.ImageCollection): The image collection to analyze.
        region (Optional[Union[ee.Geometry, ee.FeatureCollection]]): The region
            to reduce.
        region_reducer (Optional[Union[str, ee.Reducer]]): The reducer type for
            zonal statistics.Can be one of 'mean', 'median', 'sum', 'min', 'max', etc.
        scale (Optional[int]): The scale in meters at which to perform the analysis.
        year_reducer (Optional[Union[str, ee.Reducer]]): The reducer type for
            yearly statistics.
        start_day (int): The start day of the year.
        end_day (int): The end day of the year.
        chart_type (str): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
            'PieChart', 'AreaChart', and 'Table'.
        colors (Optional[List[str]]): The colors to use for the chart.
            Defaults to a predefined list of colors.
        title (Optional[str]): The title of the chart. Defaults to the
            chart type.
        x_label (Optional[str]): The label for the x-axis. Defaults to an
            empty string.
        y_label (Optional[str]): The label for the y-axis. Defaults to an
            empty string.
        **kwargs: Additional keyword arguments to pass to the bqplot Figure
            or mark objects. For axes_options, see
            https://bqplot.github.io/bqplot/api/axes

    Returns:
        Chart: The generated chart.
    """

    # Function to add day-of-year ('doy') and year properties to each image.
    def set_doys(collection):
        def add_doy(img):
            date = img.date()
            year = date.get("year")
            doy = date.getRelative("day", "year").floor().add(1)
            return img.set({"doy": doy, "year": year})

        return collection.map(add_doy)

    # Reduces images with the same day of year.
    def group_by_doy(collection, start, end, reducer):
        collection = set_doys(collection)

        doys = ee.FeatureCollection(
            [ee.Feature(None, {"doy": i}) for i in range(start, end + 1)]
        )

        # Group images by their day of year.
        filter = ee.Filter(ee.Filter.equals(leftField="doy", rightField="doy"))
        joined = ee.Join.saveAll("matches").apply(
            primary=doys, secondary=collection, condition=filter
        )

        # For each DoY, reduce images across years.
        def reduce_images(doy):
            images = ee.ImageCollection.fromImages(doy.get("matches"))
            image = images.reduce(reducer)
            return image.set(
                {
                    "doy": doy.get("doy"),
                    "geo": images.geometry(),  # // Retain geometry for future reduceRegion.
                }
            )

        return ee.ImageCollection(joined.map(reduce_images))

    # Set default values and filters if parameters are not provided.
    region_reducer = region_reducer or ee.Reducer.mean()
    year_reducer = year_reducer or ee.Reducer.mean()

    # Optionally filter the image collection by region.
    filtered_collection = image_collection
    if region:
        filtered_collection = filtered_collection.filterBounds(region)
    filtered_collection = set_doys(filtered_collection)

    doy_images = group_by_doy(filtered_collection, start_day, end_day, year_reducer)

    # For each DoY, reduce images across years within the region.
    def reduce_doy_images(image):
        region_for_image = region if region else image.get("geo")
        dictionary = image.reduceRegion(
            reducer=region_reducer, geometry=region_for_image, scale=scale
        )

        return ee.Feature(None, {"doy": image.get("doy")}).set(dictionary)

    reduced = ee.FeatureCollection(doy_images.map(reduce_doy_images))

    df = ee_to_df(reduced)
    df.columns = df.columns.str.replace(r"_.*", "", regex=True)

    x_cols = "doy"
    y_cols = df.columns.tolist()
    y_cols.remove("doy")

    fig = Chart(
        df,
        chart_type,
        x_cols,
        y_cols,
        colors,
        title,
        x_label,
        y_label,
        **kwargs,
    )
    return fig

image_doy_series_by_region(image_collection, band_name, regions, region_reducer=None, scale=None, year_reducer=None, series_property=None, start_day=1, end_day=366, chart_type='LineChart', colors=None, title=None, x_label=None, y_label=None, **kwargs)

Generates a time series chart of an image collection for multiple regions over a range of days of the year.

Parameters:

Name Type Description Default
image_collection ImageCollection

The image collection to analyze.

required
band_name str

The name of the band to analyze.

required
regions FeatureCollection

The regions to analyze.

required
region_reducer Optional[Union[str, Reducer]]

The reducer type for zonal statistics.

None
scale Optional[int]

The scale in meters at which to perform the analysis.

None
year_reducer Optional[Union[str, Reducer]]

The reducer type for yearly statistics.

None
series_property Optional[str]

The property to use for labeling the series.

None
start_day int

The start day of the year.

1
end_day int

The end day of the year.

366
chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'.

'LineChart'
colors Optional[List[str]]

The colors to use for the chart. Defaults to a predefined list of colors.

None
title Optional[str]

The title of the chart. Defaults to the chart type.

None
x_label Optional[str]

The label for the x-axis. Defaults to an empty string.

None
y_label Optional[str]

The label for the y-axis. Defaults to an empty string.

None
**kwargs Any

Additional keyword arguments to pass to the bqplot Figure or mark objects. For axes_options, see https://bqplot.github.io/bqplot/api/axes

{}

Returns:

Name Type Description
Chart Chart

The generated chart.

Source code in geemap/chart.py
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
def image_doy_series_by_region(
    image_collection: ee.ImageCollection,
    band_name: str,
    regions: ee.FeatureCollection,
    region_reducer: Optional[Union[str, ee.Reducer]] = None,
    scale: Optional[int] = None,
    year_reducer: Optional[Union[str, ee.Reducer]] = None,
    series_property: Optional[str] = None,
    start_day: int = 1,
    end_day: int = 366,
    chart_type: str = "LineChart",
    colors: Optional[List[str]] = None,
    title: Optional[str] = None,
    x_label: Optional[str] = None,
    y_label: Optional[str] = None,
    **kwargs: Any,
) -> Chart:
    """
    Generates a time series chart of an image collection for multiple regions
    over a range of days of the year.

    Args:
        image_collection (ee.ImageCollection): The image collection to analyze.
        band_name (str): The name of the band to analyze.
        regions (ee.FeatureCollection): The regions to analyze.
        region_reducer (Optional[Union[str, ee.Reducer]]): The reducer type for
            zonal statistics.
        scale (Optional[int]): The scale in meters at which to perform the analysis.
        year_reducer (Optional[Union[str, ee.Reducer]]): The reducer type for
            yearly statistics.
        series_property (Optional[str]): The property to use for labeling the series.
        start_day (int): The start day of the year.
        end_day (int): The end day of the year.
        chart_type (str): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
            'PieChart', 'AreaChart', and 'Table'.
        colors (Optional[List[str]]): The colors to use for the chart.
            Defaults to a predefined list of colors.
        title (Optional[str]): The title of the chart. Defaults to the
            chart type.
        x_label (Optional[str]): The label for the x-axis. Defaults to an
            empty string.
        y_label (Optional[str]): The label for the y-axis. Defaults to an
            empty string.
        **kwargs: Additional keyword arguments to pass to the bqplot Figure
            or mark objects. For axes_options, see
            https://bqplot.github.io/bqplot/api/axes

    Returns:
        Chart: The generated chart.
    """

    image_collection = image_collection.select(band_name)

    # Function to add day-of-year ('doy') and year properties to each image.
    def set_doys(collection):
        def add_doy(img):
            date = img.date()
            year = date.get("year")
            doy = date.getRelative("day", "year").floor().add(1)
            return img.set({"doy": doy, "year": year})

        return collection.map(add_doy)

    # Reduces images with the same day of year.
    def group_by_doy(collection, start, end, reducer):
        collection = set_doys(collection)

        doys = ee.FeatureCollection(
            [ee.Feature(None, {"doy": i}) for i in range(start, end + 1)]
        )

        # Group images by their day of year.
        filter = ee.Filter(ee.Filter.equals(leftField="doy", rightField="doy"))
        joined = ee.Join.saveAll("matches").apply(
            primary=doys, secondary=collection, condition=filter
        )

        # For each DoY, reduce images across years.
        def reduce_images(doy):
            images = ee.ImageCollection.fromImages(doy.get("matches"))
            image = images.reduce(reducer)
            return image.set(
                {
                    "doy": doy.get("doy"),
                    "geo": images.geometry(),  # // Retain geometry for future reduceRegion.
                }
            )

        return ee.ImageCollection(joined.map(reduce_images))

    if year_reducer is None:
        year_reducer = ee.Reducer.mean()
    if region_reducer is None:
        region_reducer = ee.Reducer.mean()

    doy_images = group_by_doy(image_collection, start_day, end_day, year_reducer)

    if series_property is None:
        series_property = "system:index"
    regions = regions.select([series_property])
    fc = zonal_stats(
        doy_images.toBands(),
        regions,
        stat_type=region_reducer,
        scale=scale,
        verbose=False,
        return_fc=True,
    )
    df = ee_to_df(fc)
    df = transpose_df(df, label_col=series_property, index_name="doy")
    df["doy"] = df.index.str.split("_").str[0].astype(int)
    df.sort_values("doy", inplace=True)
    y_cols = df.columns.tolist()
    y_cols.remove("doy")

    fig = Chart(
        df,
        chart_type,
        "doy",
        y_cols,
        colors,
        title,
        x_label,
        y_label,
        **kwargs,
    )
    return fig

image_histogram(image, region, scale, max_buckets, min_bucket_width, max_raw, max_pixels, reducer_args={}, **kwargs)

Creates a histogram for each band of the specified image within the given region using bqplot.

Parameters:

Name Type Description Default
image Image

The Earth Engine image for which to create histograms.

required
region Geometry

The region over which to calculate the histograms.

required
scale int

The scale in meters of the calculation.

required
max_buckets int

The maximum number of buckets in the histogram.

required
min_bucket_width float

The minimum width of the buckets in the histogram.

required
max_raw int

The maximum number of pixels to include in the histogram.

required
max_pixels int

The maximum number of pixels to reduce.

required
reducer_args Dict[str, Any]

Additional arguments to pass to the image.reduceRegion.

{}

Other Parameters:

Name Type Description
colors List[str]

Colors for the histograms of each band.

labels List[str]

Labels for the histograms of each band.

title str

Title of the combined histogram plot.

legend_location str

Location of the legend in the plot.

Returns:

Type Description
Figure

bq.Figure: The bqplot figure containing the histograms.

Source code in geemap/chart.py
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
def image_histogram(
    image: ee.Image,
    region: ee.Geometry,
    scale: int,
    max_buckets: int,
    min_bucket_width: float,
    max_raw: int,
    max_pixels: int,
    reducer_args: Dict[str, Any] = {},
    **kwargs: Dict[str, Any],
) -> bq.Figure:
    """
    Creates a histogram for each band of the specified image within the given
    region using bqplot.

    Args:
        image (ee.Image): The Earth Engine image for which to create histograms.
        region (ee.Geometry): The region over which to calculate the histograms.
        scale (int): The scale in meters of the calculation.
        max_buckets (int): The maximum number of buckets in the histogram.
        min_bucket_width (float): The minimum width of the buckets in the histogram.
        max_raw (int): The maximum number of pixels to include in the histogram.
        max_pixels (int): The maximum number of pixels to reduce.
        reducer_args (Dict[str, Any]): Additional arguments to pass to the image.reduceRegion.

    Keyword Args:
        colors (List[str]): Colors for the histograms of each band.
        labels (List[str]): Labels for the histograms of each band.
        title (str): Title of the combined histogram plot.
        legend_location (str): Location of the legend in the plot.

    Returns:
        bq.Figure: The bqplot figure containing the histograms.
    """
    # Calculate the histogram data.
    histogram = image.reduceRegion(
        reducer=ee.Reducer.histogram(
            maxBuckets=max_buckets, minBucketWidth=min_bucket_width, maxRaw=max_raw
        ),
        geometry=region,
        scale=scale,
        maxPixels=max_pixels,
        **reducer_args,
    )

    histograms = {
        band: histogram.get(band).getInfo() for band in image.bandNames().getInfo()
    }

    # Create bqplot histograms for each band.
    def create_histogram(
        hist_data: Dict[str, Any], color: str, label: str
    ) -> bq.Figure:
        """
        Creates a bqplot histogram for the given histogram data.

        Args:
            hist_data (dict): The histogram data.
            color (str): The color of the histogram.
            label (str): The label of the histogram.

        Returns:
            bq.Figure: The bqplot figure for the histogram.
        """
        x_data = np.array(hist_data["bucketMeans"])
        y_data = np.array(hist_data["histogram"])

        x_sc = bq.LinearScale()
        y_sc = bq.LinearScale()

        bar = bq.Bars(
            x=x_data,
            y=y_data,
            scales={"x": x_sc, "y": y_sc},
            colors=[color],
            display_legend=True,
            labels=[label],
        )

        ax_x = bq.Axis(scale=x_sc, label="Reflectance (x1e4)", tick_format="0.0f")
        ax_y = bq.Axis(
            scale=y_sc, orientation="vertical", label="Count", tick_format="0.0f"
        )

        return bq.Figure(marks=[bar], axes=[ax_x, ax_y])

    # Define colors and labels for the bands.
    band_colors = kwargs.get("colors", ["#cf513e", "#1d6b99", "#f0af07"])
    band_labels = kwargs.get("labels", image.bandNames().getInfo())

    # Create and combine histograms for each band.
    histograms_fig = []
    for band, color, label in zip(histograms.keys(), band_colors, band_labels):
        histograms_fig.append(create_histogram(histograms[band], color, label))

    combined_fig = bq.Figure(
        marks=[fig.marks[0] for fig in histograms_fig],
        axes=histograms_fig[0].axes,
        **kwargs,
    )

    for fig, label in zip(histograms_fig, band_labels):
        fig.marks[0].labels = [label]

    combined_fig.legend_location = kwargs.get("legend_location", "top-right")

    return combined_fig

image_regions(image, regions, reducer, scale, series_property, x_labels, **kwargs)

Generates a Chart from an image by regions. Extracts and plots band values in multiple regions.

Parameters:

Name Type Description Default
image Image

Image to extract band values from.

required
regions Union[FeatureCollection, Geometry]

Regions to reduce. Defaults to the image's footprint.

required
reducer Union[str, Reducer]

The reducer type for zonal statistics. Can be one of 'mean', 'median', 'sum', 'min', 'max', etc.

required
scale int

The scale in meters at which to perform the analysis.

required
series_property str

The property to use for labeling the series.

required
x_labels List[str]

List of x-axis labels.

required
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
None

bq.Figure: The bqplot figure.

Source code in geemap/chart.py
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
def image_regions(
    image: ee.Image,
    regions: Union[ee.FeatureCollection, ee.Geometry],
    reducer: Union[str, ee.Reducer],
    scale: int,
    series_property: str,
    x_labels: List[str],
    **kwargs: Any,
) -> None:
    """
    Generates a Chart from an image by regions. Extracts and plots band values
    in multiple regions.

    Args:
        image (ee.Image): Image to extract band values from.
        regions (Union[ee.FeatureCollection, ee.Geometry]): Regions to reduce.
            Defaults to the image's footprint.
        reducer (Union[str, ee.Reducer]): The reducer type for zonal statistics.
            Can be one of 'mean', 'median', 'sum', 'min', 'max', etc.
        scale (int): The scale in meters at which to perform the analysis.
        series_property (str): The property to use for labeling the series.
        x_labels (List[str]): List of x-axis labels.
        **kwargs: Additional keyword arguments.

    Returns:
        bq.Figure: The bqplot figure.
    """
    fc = zonal_stats(
        image, regions, stat_type=reducer, scale=scale, verbose=False, return_fc=True
    )
    bands = image.bandNames().getInfo()
    fc = fc.select(bands + [series_property])
    return feature_by_property(fc, x_labels, series_property, **kwargs)

image_series(image_collection, region, reducer=None, scale=None, x_property='system:time_start', chart_type='LineChart', x_cols=None, y_cols=None, colors=None, title=None, x_label=None, y_label=None, **kwargs)

Generates a time series chart of an image collection for a specific region.

Parameters:

Name Type Description Default
image_collection ImageCollection

The image collection to analyze.

required
region Union[Geometry, FeatureCollection]

The region to reduce.

required
reducer Optional[Union[str, Reducer]]

The reducer to use.

None
scale Optional[int]

The scale in meters at which to perform the analysis.

None
x_property str

The name of the property to use as the x-axis values.

'system:time_start'
chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'.

'LineChart'
x_cols Optional[List[str]]

The columns to use for the x-axis. Defaults to the first column.

None
y_cols Optional[List[str]]

The columns to use for the y-axis. Defaults to the second column.

None
colors Optional[List[str]]

The colors to use for the chart. Defaults to a predefined list of colors.

None
title Optional[str]

The title of the chart. Defaults to the chart type.

None
x_label Optional[str]

The label for the x-axis. Defaults to an empty string.

None
y_label Optional[str]

The label for the y-axis. Defaults to an empty string.

None
**kwargs Any

Additional keyword arguments to pass to the bqplot Figure or mark objects. For axes_options, see https://bqplot.github.io/bqplot/api/axes

{}

Returns:

Name Type Description
Chart Chart

The chart object.

Source code in geemap/chart.py
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
def image_series(
    image_collection: ee.ImageCollection,
    region: Union[ee.Geometry, ee.FeatureCollection],
    reducer: Optional[Union[str, ee.Reducer]] = None,
    scale: Optional[int] = None,
    x_property: str = "system:time_start",
    chart_type: str = "LineChart",
    x_cols: Optional[List[str]] = None,
    y_cols: Optional[List[str]] = None,
    colors: Optional[List[str]] = None,
    title: Optional[str] = None,
    x_label: Optional[str] = None,
    y_label: Optional[str] = None,
    **kwargs: Any,
) -> Chart:
    """
    Generates a time series chart of an image collection for a specific region.

    Args:
        image_collection (ee.ImageCollection): The image collection to analyze.
        region (Union[ee.Geometry, ee.FeatureCollection]): The region to reduce.
        reducer (Optional[Union[str, ee.Reducer]]): The reducer to use.
        scale (Optional[int]): The scale in meters at which to perform the analysis.
        x_property (str): The name of the property to use as the x-axis values.
        chart_type (str): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
            'PieChart', 'AreaChart', and 'Table'.
        x_cols (Optional[List[str]]): The columns to use for the x-axis.
            Defaults to the first column.
        y_cols (Optional[List[str]]): The columns to use for the y-axis.
            Defaults to the second column.
        colors (Optional[List[str]]): The colors to use for the chart.
            Defaults to a predefined list of colors.
        title (Optional[str]): The title of the chart. Defaults to the
            chart type.
        x_label (Optional[str]): The label for the x-axis. Defaults to an
            empty string.
        y_label (Optional[str]): The label for the y-axis. Defaults to an
            empty string.
        **kwargs: Additional keyword arguments to pass to the bqplot Figure
            or mark objects. For axes_options, see
            https://bqplot.github.io/bqplot/api/axes

    Returns:
        Chart: The chart object.
    """

    if reducer is None:
        reducer = ee.Reducer.mean()

    band_names = image_collection.first().bandNames().getInfo()

    # Function to reduce the region and get the mean for each image.
    def get_stats(image):
        stats = image.reduceRegion(reducer=reducer, geometry=region, scale=scale)

        results = {}
        for band in band_names:
            results[band] = stats.get(band)

        if x_property == "system:time_start" or x_property == "system:time_end":
            results["date"] = image.date().format("YYYY-MM-dd")
        else:
            results[x_property] = image.get(x_property).getInfo()

        return ee.Feature(None, results)

    # Apply the function over the image collection.
    fc = ee.FeatureCollection(
        image_collection.map(get_stats).filter(ee.Filter.notNull(band_names))
    )
    df = ee_to_df(fc)
    if "date" in df.columns:
        df["date"] = pd.to_datetime(df["date"])

    fig = Chart(
        df,
        chart_type,
        x_cols,
        y_cols,
        colors,
        title,
        x_label,
        y_label,
        **kwargs,
    )
    return fig

image_series_by_region(image_collection, regions, reducer=None, band=None, scale=None, x_property='system:time_start', series_property='system:index', chart_type='LineChart', x_cols=None, y_cols=None, colors=None, title=None, x_label=None, y_label=None, **kwargs)

Generates a time series chart of an image collection for multiple regions.

Parameters:

Name Type Description Default
image_collection ImageCollection

The image collection to analyze.

required
regions FeatureCollection | Geometry

The regions to reduce.

required
reducer str | Reducer

The reducer type for zonal statistics.

None
band str

The name of the band to analyze.

None
scale int

The scale in meters at which to perform the analysis.

None
x_property str

The name of the property to use as the x-axis values.

'system:time_start'
series_property str

The property to use for labeling the series.

'system:index'
chart_type str

The type of chart to create. Supported types are 'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart', 'PieChart', 'AreaChart', and 'Table'.

'LineChart'
x_cols Optional[List[str]]

The columns to use for the x-axis. Defaults to the first column.

None
y_cols Optional[List[str]]

The columns to use for the y-axis. Defaults to the second column.

None
colors Optional[List[str]]

The colors to use for the chart. Defaults to a predefined list of colors.

None
title Optional[str]

The title of the chart. Defaults to the chart type.

None
x_label Optional[str]

The label for the x-axis. Defaults to an empty string.

None
y_label Optional[str]

The label for the y-axis. Defaults to an empty string.

None
**kwargs Any

Additional keyword arguments to pass to the bqplot Figure or mark objects. For axes_options, see https://bqplot.github.io/bqplot/api/axes

{}

Returns:

Name Type Description
Chart Chart

The chart object.

Source code in geemap/chart.py
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
def image_series_by_region(
    image_collection: ee.ImageCollection,
    regions: Union[ee.FeatureCollection, ee.Geometry],
    reducer: Optional[Union[str, ee.Reducer]] = None,
    band: Optional[str] = None,
    scale: Optional[int] = None,
    x_property: str = "system:time_start",
    series_property: str = "system:index",
    chart_type: str = "LineChart",
    x_cols: Optional[List[str]] = None,
    y_cols: Optional[List[str]] = None,
    colors: Optional[List[str]] = None,
    title: Optional[str] = None,
    x_label: Optional[str] = None,
    y_label: Optional[str] = None,
    **kwargs: Any,
) -> Chart:
    """
    Generates a time series chart of an image collection for multiple regions.

    Args:
        image_collection (ee.ImageCollection): The image collection to analyze.
        regions (ee.FeatureCollection | ee.Geometry): The regions to reduce.
        reducer (str | ee.Reducer): The reducer type for zonal statistics.
        band (str): The name of the band to analyze.
        scale (int): The scale in meters at which to perform the analysis.
        x_property (str): The name of the property to use as the x-axis values.
        series_property (str): The property to use for labeling the series.
        chart_type (str): The type of chart to create. Supported types are
            'ScatterChart', 'LineChart', 'ColumnChart', 'BarChart',
            'PieChart', 'AreaChart', and 'Table'.
        x_cols (Optional[List[str]]): The columns to use for the x-axis.
            Defaults to the first column.
        y_cols (Optional[List[str]]): The columns to use for the y-axis.
            Defaults to the second column.
        colors (Optional[List[str]]): The colors to use for the chart.
            Defaults to a predefined list of colors.
        title (Optional[str]): The title of the chart. Defaults to the
            chart type.
        x_label (Optional[str]): The label for the x-axis. Defaults to an
            empty string.
        y_label (Optional[str]): The label for the y-axis. Defaults to an
            empty string.
        **kwargs: Additional keyword arguments to pass to the bqplot Figure
            or mark objects. For axes_options, see
            https://bqplot.github.io/bqplot/api/axes

    Returns:
        Chart: The chart object.
    """
    if reducer is None:
        reducer = ee.Reducer.mean()

    if band is None:
        band = image_collection.first().bandNames().get(0).getInfo()

    image = image_collection.select(band).toBands()

    fc = zonal_stats(
        image, regions, stat_type=reducer, scale=scale, verbose=False, return_fc=True
    )
    columns = image.bandNames().getInfo() + [series_property]
    df = ee_to_df(fc, columns=columns)

    headers = df[series_property].tolist()
    df = df.drop(columns=[series_property]).T
    df.columns = headers

    if x_property == "system:time_start" or x_property == "system:time_end":
        indexes = image_dates(image_collection).getInfo()
        df["index"] = pd.to_datetime(indexes)

    else:
        indexes = image_collection.aggregate_array(x_property).getInfo()
        df["index"] = indexes

    fig = Chart(
        df,
        chart_type,
        x_cols,
        y_cols,
        colors,
        title,
        x_label,
        y_label,
        **kwargs,
    )
    return fig

pivot_df(df, index, columns, values)

Pivots a DataFrame using the specified index, columns, and values.

Parameters:

Name Type Description Default
df DataFrame

The DataFrame to pivot.

required
index str

The column to use for the index.

required
columns str

The column to use for the columns.

required
values str

The column to use for the values.

required

Returns:

Type Description
DataFrame

pd.DataFrame: The pivoted DataFrame.

Source code in geemap/chart.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def pivot_df(df: pd.DataFrame, index: str, columns: str, values: str) -> pd.DataFrame:
    """
    Pivots a DataFrame using the specified index, columns, and values.

    Args:
        df (pd.DataFrame): The DataFrame to pivot.
        index (str): The column to use for the index.
        columns (str): The column to use for the columns.
        values (str): The column to use for the values.

    Returns:
        pd.DataFrame: The pivoted DataFrame.
    """
    df_pivot = df.pivot(index=index, columns=columns, values=values).reset_index()
    df_pivot.columns = [index] + [f"{col}" for col in df_pivot.columns[1:]]
    return df_pivot

transpose_df(df, label_col, index_name=None, indexes=None)

Transposes a pandas DataFrame and optionally sets a new index name and custom indexes.

Parameters:

Name Type Description Default
df DataFrame

The DataFrame to transpose.

required
label_col str

The column to set as the index before transposing.

required
index_name str

The name to set for the index after transposing. Defaults to None.

None
indexes list

A list of custom indexes to set after transposing. The length of this list must match the number of rows in the transposed DataFrame. Defaults to None.

None

Returns:

Type Description
DataFrame

pd.DataFrame: The transposed DataFrame.

Raises:

Type Description
ValueError

If label_col is not a column in the DataFrame.

ValueError

If the length of indexes does not match the number of rows in the transposed DataFrame.

Source code in geemap/chart.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def transpose_df(
    df: pd.DataFrame,
    label_col: str,
    index_name: str = None,
    indexes: list = None,
) -> pd.DataFrame:
    """
    Transposes a pandas DataFrame and optionally sets a new index name and
        custom indexes.

    Args:
        df (pd.DataFrame): The DataFrame to transpose.
        label_col (str): The column to set as the index before transposing.
        index_name (str, optional): The name to set for the index after
            transposing. Defaults to None.
        indexes (list, optional): A list of custom indexes to set after
            transposing. The length of this list must match the number of rows
            in the transposed DataFrame. Defaults to None.

    Returns:
        pd.DataFrame: The transposed DataFrame.

    Raises:
        ValueError: If `label_col` is not a column in the DataFrame.
        ValueError: If the length of `indexes` does not match the number of
            rows in the transposed DataFrame.
    """
    # Check if the specified column exists in the DataFrame
    if label_col not in df.columns:
        raise ValueError(f"Column '{label_col}' not found in DataFrame")

    # Set the specified column as the index
    transposed_df = df.set_index(label_col).transpose()

    # Set the index name if provided
    if index_name:
        transposed_df.columns.name = index_name

    # Set custom indexes if provided
    if indexes:
        if len(indexes) != len(transposed_df.index):
            raise ValueError(
                "Length of custom indexes must match the number of rows in the transposed DataFrame"
            )
        transposed_df.index = indexes

    return transposed_df