Skip to content

TablePlotter

A class that contains plotting methods for a table.

Parameters:

Name Type Description Default
table Table

The table to plot.

required

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table({"test": [1, 2, 3]})
>>> plotter = table.plot

Methods:

Name Description
box_plots

Create a box plot for every numerical column.

correlation_heatmap

Plot a correlation heatmap for all numerical columns of this Table.

histogram_2d

Create a 2D histogram for two columns in the table.

histograms

Plot a histogram for every column.

line_plot

Create a line plot for two columns in the table.

moving_average_plot

Create a moving average plot for the y column and plot it by the x column in the table.

scatter_plot

Create a scatter plot for two columns in the table.

violin_plots

Create a violin plot for every numerical column.

Source code in src/safeds/data/tabular/plotting/_table_plotter.py
 17
 18
 19
 20
 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
 54
 55
 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
177
178
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
502
503
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
585
586
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
676
677
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
727
728
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
class TablePlotter:
    """
    A class that contains plotting methods for a table.

    Parameters
    ----------
    table:
        The table to plot.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table({"test": [1, 2, 3]})
    >>> plotter = table.plot
    """

    def __init__(self, table: Table):
        self._table: Table = table

    # ------------------------------------------------------------------------------------------------------------------
    # Gridded plots for individual columns
    # ------------------------------------------------------------------------------------------------------------------

    def box_plots(self, *, theme: Literal["dark", "light"] = "light") -> Image:
        """
        Create a box plot for every numerical column.

        Parameters
        ----------
        theme:
            The color theme of the plot. Default is "light".

        Returns
        -------
        plot:
            The box plot(s) as an image.

        Raises
        ------
        NonNumericColumnError
            If the table contains only non-numerical columns.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table({"a":[1, 2], "b": [3, 42]})
        >>> image = table.plot.box_plots()
        """
        numerical_table = self._table.remove_non_numeric_columns()
        if numerical_table.column_count == 0:
            raise NonNumericColumnError("This table contains only non-numerical columns.")
        from math import ceil

        import matplotlib.pyplot as plt

        style = "dark_background" if theme == "dark" else "default"
        with plt.style.context(style):
            if theme == "dark":
                plt.rcParams.update(
                    {
                        "text.color": "white",
                        "axes.labelcolor": "white",
                        "axes.edgecolor": "white",
                        "xtick.color": "white",
                        "ytick.color": "white",
                    },
                )
            columns = numerical_table.to_columns()
            columns = [column._series.drop_nulls() for column in columns]
            max_width = 3
            number_of_columns = len(columns) if len(columns) <= max_width else max_width
            number_of_rows = ceil(len(columns) / number_of_columns)

            fig, axs = plt.subplots(nrows=number_of_rows, ncols=number_of_columns)
            line = 0
            for i, column in enumerate(columns):
                if i % number_of_columns == 0 and i != 0:
                    line += 1

                if number_of_columns == 1:
                    axs.boxplot(
                        column,
                        patch_artist=True,
                        tick_labels=[numerical_table.column_names[i]],
                    )
                    break

                if number_of_rows == 1:
                    axs[i].boxplot(
                        column,
                        patch_artist=True,
                        tick_labels=[numerical_table.column_names[i]],
                    )

                else:
                    axs[line, i % number_of_columns].boxplot(
                        column,
                        patch_artist=True,
                        tick_labels=[numerical_table.column_names[i]],
                    )

            # removes unused ax indices, so there wont be empty plots
            last_filled_ax_index = len(columns) % number_of_columns
            for i in range(last_filled_ax_index, number_of_columns):
                if number_of_rows != 1 and last_filled_ax_index != 0:
                    fig.delaxes(axs[number_of_rows - 1, i])

            fig.tight_layout()
            return _figure_to_image(fig)

    def histograms(self, *, max_bin_count: int = 10, theme: Literal["dark", "light"] = "light") -> Image:
        """
        Plot a histogram for every column.

        Parameters
        ----------
        max_bin_count:
            The maximum number of bins to use in the histogram. Default is 10.
        theme:
            The color theme of the plot. Default is "light".

        Returns
        -------
        plot:
            The plot as an image.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table({"a": [2, 3, 5, 1], "b": [54, 74, 90, 2014]})
        >>> image = table.plot.histograms()
        """
        import matplotlib.pyplot as plt

        style = "dark_background" if theme == "dark" else "default"
        with plt.style.context(style):
            if theme == "dark":
                plt.rcParams.update(
                    {
                        "text.color": "white",
                        "axes.labelcolor": "white",
                        "axes.edgecolor": "white",
                        "xtick.color": "white",
                        "ytick.color": "white",
                    },
                )
            import polars as pl

            n_cols = min(3, self._table.column_count)
            n_rows = 1 + (self._table.column_count - 1) // n_cols

            if n_cols == 1 and n_rows == 1:
                fig, axs = plt.subplots(1, 1, tight_layout=True)
                one_col = True
            else:
                fig, axs = plt.subplots(n_rows, n_cols, tight_layout=True, figsize=(n_cols * 3, n_rows * 3))
                one_col = False

            col_names = self._table.column_names
            for col_name, ax in zip(col_names, axs.flatten() if not one_col else [axs], strict=False):
                column = self._table.get_column(col_name)
                distinct_values = column.get_distinct_values()

                ax.set_title(col_name)
                ax.set_xlabel("")
                ax.set_ylabel("")

                if column.type.is_numeric and len(distinct_values) > max_bin_count:
                    min_val = (column.min() or 0) - 1e-6  # Otherwise the minimum value is not included in the first bin
                    max_val = column.max() or 0
                    bin_count = min(max_bin_count, len(distinct_values))
                    bins = [
                        *(pl.Series(range(bin_count + 1)) / bin_count * (max_val - min_val) + min_val),
                    ]

                    bars = [f"{round((bins[i] + bins[i + 1]) / 2, 2)}" for i in range(len(bins) - 1)]
                    hist = column._series.hist(bins=bins).get_column("count").to_numpy()

                    ax.bar(bars, hist, edgecolor="black")
                    ax.set_xticks(range(len(hist)), bars, rotation=45, horizontalalignment="right")
                else:
                    value_counts = (
                        column._series.drop_nulls().value_counts().sort(column.name).slice(0, length=max_bin_count)
                    )
                    distinct_values = value_counts.get_column(column.name).cast(pl.String).to_numpy()
                    hist = value_counts.get_column("count").to_numpy()
                    ax.bar(distinct_values, hist, edgecolor="black")
                    ax.set_xticks(
                        range(len(distinct_values)),
                        distinct_values,
                        rotation=45,
                        horizontalalignment="right",
                    )

            for i in range(len(col_names), n_rows * n_cols):
                fig.delaxes(axs.flatten()[i])  # Remove empty subplots

            return _figure_to_image(fig)

    def violin_plots(self, *, theme: Literal["dark", "light"] = "light") -> Image:
        """
        Create a violin plot for every numerical column.

        Parameters
        ----------
        theme:
            The color theme of the plot. Default is "light".

        Returns
        -------
        plot:
            The violin plot(s) as an image.

        Raises
        ------
        NonNumericColumnError
            If the table contains only non-numerical columns.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table({"a": [1, 2], "b": [3, 42]})
        >>> image = table.plot.violin_plots()
        """
        numerical_table = self._table.remove_non_numeric_columns()
        if numerical_table.column_count == 0:
            raise NonNumericColumnError("This table contains only non-numerical columns.")
        from math import ceil

        import matplotlib.pyplot as plt

        style = "dark_background" if theme == "dark" else "default"
        with plt.style.context(style):
            if theme == "dark":
                plt.rcParams.update(
                    {
                        "text.color": "white",
                        "axes.labelcolor": "white",
                        "axes.edgecolor": "white",
                        "xtick.color": "white",
                        "ytick.color": "white",
                        "grid.color": "gray",
                        "grid.linewidth": 0.5,
                    },
                )
            else:
                plt.rcParams.update(
                    {
                        "grid.linewidth": 0.5,
                    },
                )

            columns = numerical_table.to_columns()
            columns = [column._series.drop_nulls() for column in columns]
            max_width = 3
            number_of_columns = len(columns) if len(columns) <= max_width else max_width
            number_of_rows = ceil(len(columns) / number_of_columns)

            fig, axs = plt.subplots(nrows=number_of_rows, ncols=number_of_columns)
            line = 0
            for i, column in enumerate(columns):
                data = column.to_list()

                if i % number_of_columns == 0 and i != 0:
                    line += 1

                if number_of_columns == 1:
                    axs.violinplot(
                        data,
                    )
                    axs.set_title(numerical_table.column_names[i])
                    break

                if number_of_rows == 1:
                    axs[i].violinplot(
                        data,
                    )
                    axs[i].set_title(numerical_table.column_names[i])

                else:
                    axs[line, i % number_of_columns].violinplot(
                        data,
                    )
                    axs[line, i % number_of_columns].set_title(numerical_table.column_names[i])

            # removes unused ax indices, so there wont be empty plots
            last_filled_ax_index = len(columns) % number_of_columns
            for i in range(last_filled_ax_index, number_of_columns):
                if number_of_rows != 1 and last_filled_ax_index != 0:
                    fig.delaxes(axs[number_of_rows - 1, i])

            fig.tight_layout()
            return _figure_to_image(fig)

    # ------------------------------------------------------------------------------------------------------------------
    # Plots for two columns
    # ------------------------------------------------------------------------------------------------------------------

    def line_plot(
        self,
        x_name: str,
        y_names: list[str],
        *,
        show_confidence_interval: bool = True,
        theme: Literal["dark", "light"] = "light",
    ) -> Image:
        """
        Create a line plot for two columns in the table.

        Parameters
        ----------
        x_name:
            The name of the column to be plotted on the x-axis.
        y_names:
            The name(s) of the column(s) to be plotted on the y-axis.
        show_confidence_interval:
            If the confidence interval is shown, per default True.
        theme:
            The color theme of the plot. Default is "light".

        Returns
        -------
        plot:
            The plot as an image.

        Raises
        ------
        ColumnNotFoundError
            If a column does not exist.
        TypeError
            If a column is not numeric.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table(
        ...     {
        ...         "a": [1, 2, 3, 4, 5],
        ...         "b": [2, 3, 4, 5, 6],
        ...     }
        ... )
        >>> image = table.plot.line_plot("a", ["b"])
        """
        _plot_validation(self._table, x_name, y_names)

        import matplotlib.pyplot as plt

        style = "dark_background" if theme == "dark" else "default"
        with plt.style.context(style):
            if theme == "dark":
                plt.rcParams.update(
                    {
                        "text.color": "white",
                        "axes.labelcolor": "white",
                        "axes.edgecolor": "white",
                        "xtick.color": "white",
                        "ytick.color": "white",
                    },
                )
            import polars as pl

            agg_list = []
            for name in y_names:
                agg_list.append(pl.col(name).mean().alias(f"{name}_mean"))
                agg_list.append(pl.count(name).alias(f"{name}_count"))
                agg_list.append(pl.std(name, ddof=0).alias(f"{name}_std"))
            grouped_lazy = self._table._lazy_frame.sort(x_name).group_by(x_name, maintain_order=True).agg(agg_list)
            grouped = _safe_collect_lazy_frame(grouped_lazy)

            x = grouped.get_column(x_name)
            y_s = []
            confidence_intervals = []
            for name in y_names:
                y_s.append(grouped.get_column(name + "_mean"))
                confidence_intervals.append(
                    1.96 * grouped.get_column(name + "_std") / grouped.get_column(name + "_count").sqrt(),
                )

            fig, ax = plt.subplots()
            for name, y in zip(y_names, y_s, strict=False):
                ax.plot(x, y, label=name)

            if show_confidence_interval:
                for y, conf in zip(y_s, confidence_intervals, strict=False):
                    ax.fill_between(
                        x,
                        y - conf,
                        y + conf,
                        color="lightblue",
                        alpha=0.15,
                    )
            if len(y_names) > 1:
                name = "values"
            else:
                name = y_names[0]
            ax.set(
                xlabel=x_name,
                ylabel=name,
            )
            ax.legend()
            ax.set_xticks(ax.get_xticks())
            ax.set_xticklabels(
                ax.get_xticklabels(),
                rotation=45,
                horizontalalignment="right",
            )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
            fig.tight_layout()

            return _figure_to_image(fig)

    def histogram_2d(
        self,
        x_name: str,
        y_name: str,
        *,
        x_max_bin_count: int = 10,
        y_max_bin_count: int = 10,
        theme: Literal["dark", "light"] = "light",
    ) -> Image:
        """
        Create a 2D histogram for two columns in the table.

        Parameters
        ----------
        x_name:
            The name of the column to be plotted on the x-axis.
        y_name:
            The name of the column to be plotted on the y-axis.
        x_max_bin_count:
            The maximum number of bins to use in the histogram for the x-axis. Default is 10.
        y_max_bin_count:
            The maximum number of bins to use in the histogram for the y-axis. Default is 10.
        theme:
            The color theme of the plot. Default is "light".

        Returns
        -------
        plot:
            The plot as an image.

        Raises
        ------
        ColumnNotFoundError
            If a column does not exist.
        OutOfBoundsError:
            If x_max_bin_count or y_max_bin_count is less than 1.
        TypeError
            If a column is not numeric.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table(
        ...     {
        ...         "a": [1, 2, 3, 4, 5],
        ...         "b": [2, 3, 4, 5, 6],
        ...     }
        ... )
        >>> image = table.plot.histogram_2d("a", "b")
        """
        _check_bounds("x_max_bin_count", x_max_bin_count, lower_bound=_ClosedBound(1))
        _check_bounds("y_max_bin_count", y_max_bin_count, lower_bound=_ClosedBound(1))
        _plot_validation(self._table, x_name, [y_name])

        import matplotlib.pyplot as plt

        if theme == "dark":
            context = "dark_background"
        else:
            context = "default"

        with plt.style.context(context):
            fig, ax = plt.subplots()

            ax.hist2d(
                x=self._table.get_column(x_name)._series,
                y=self._table.get_column(y_name)._series,
                bins=(x_max_bin_count, y_max_bin_count),
            )
            ax.set_xlabel(x_name)
            ax.set_ylabel(y_name)
            ax.tick_params(
                axis="x",
                labelrotation=45,
            )

            fig.tight_layout()

            return _figure_to_image(fig)

    def moving_average_plot(
        self,
        x_name: str,
        y_name: str,
        window_size: int,
        *,
        theme: Literal["dark", "light"] = "light",
    ) -> Image:
        """
        Create a moving average plot for the y column and plot it by the x column in the table.

        Parameters
        ----------
        x_name:
            The name of the column to be plotted on the x-axis.
        y_name:
            The name of the column to be plotted on the y-axis.
        window_size:
            The size of the moving average window
        theme:
            The color theme of the plot. Default is "light".

        Returns
        -------
        plot:
            The plot as an image.

        Raises
        ------
        ColumnNotFoundError
            If a column does not exist.
        TypeError
            If a column is not numeric.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table(
        ...     {
        ...         "a": [1, 2, 3, 4, 5],
        ...         "b": [2, 3, 4, 5, 6],
        ...     }
        ... )
        >>> image = table.plot.moving_average_plot("a", "b", window_size = 2)
        """
        import matplotlib.pyplot as plt

        style = "dark_background" if theme == "dark" else "default"
        with plt.style.context(style):
            if theme == "dark":
                plt.rcParams.update(
                    {
                        "text.color": "white",
                        "axes.labelcolor": "white",
                        "axes.edgecolor": "white",
                        "xtick.color": "white",
                        "ytick.color": "white",
                    },
                )
            import numpy as np
            import polars as pl

            _plot_validation(self._table, x_name, [y_name])
            for name in [x_name, y_name]:
                if self._table.get_column(name).missing_value_count() >= 1:
                    raise ValueError(
                        f"there are missing values in column '{name}', use transformation to fill missing values "
                        f"or drop the missing values. For a moving average no missing values are allowed.",
                    )

            # Calculate the moving average
            mean_col = pl.col(y_name).mean().alias(y_name)
            grouped_lazy = self._table._lazy_frame.sort(x_name).group_by(x_name, maintain_order=True).agg(mean_col)
            data = _safe_collect_lazy_frame(grouped_lazy)
            moving_average = data.select([pl.col(y_name).rolling_mean(window_size).alias("moving_average")])
            # set up the arrays for plotting
            y_data_with_nan = moving_average["moving_average"].to_numpy()
            nan_mask = ~np.isnan(y_data_with_nan)
            y_data = y_data_with_nan[nan_mask]
            x_data = data[x_name].to_numpy()[nan_mask]
            fig, ax = plt.subplots()
            ax.plot(x_data, y_data, label="moving average")
            ax.set(
                xlabel=x_name,
                ylabel=y_name,
            )
            ax.legend()
            if self._table.get_column_type(x_name).is_temporal and self._table.get_column(x_name).row_count < 9:
                ax.set_xticks(x_data)  # Set x-ticks to the x data points
            ax.set_xticks(ax.get_xticks())
            ax.set_xticklabels(
                ax.get_xticklabels(),
                rotation=45,
                horizontalalignment="right",
            )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
            fig.tight_layout()

            return _figure_to_image(fig)

    def scatter_plot(self, x_name: str, y_names: list[str], *, theme: Literal["dark", "light"] = "light") -> Image:
        """
        Create a scatter plot for two columns in the table.

        Parameters
        ----------
        x_name:
            The name of the column to be plotted on the x-axis.
        y_names:
            The name(s) of the column(s) to be plotted on the y-axis.
        theme:
            The color theme of the plot. Default is "light".

        Returns
        -------
        plot:
            The plot as an image.

        Raises
        ------
        ColumnNotFoundError
            If a column does not exist.
        TypeError
            If a column is not numeric.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table(
        ...     {
        ...         "a": [1, 2, 3, 4, 5],
        ...         "b": [2, 3, 4, 5, 6],
        ...     }
        ... )
        >>> image = table.plot.scatter_plot("a", ["b"])
        """
        _plot_validation(self._table, x_name, y_names)

        import matplotlib.pyplot as plt

        style = "dark_background" if theme == "dark" else "default"
        with plt.style.context(style):
            if theme == "dark":
                plt.rcParams.update(
                    {
                        "text.color": "white",
                        "axes.labelcolor": "white",
                        "axes.edgecolor": "white",
                        "xtick.color": "white",
                        "ytick.color": "white",
                    },
                )
            fig, ax = plt.subplots()
            for y_name in y_names:
                ax.scatter(
                    x=self._table.get_column(x_name)._series,
                    y=self._table.get_column(y_name)._series,
                    s=64,  # marker size
                    linewidth=1,
                    edgecolor="white",
                    label=y_name,
                )
            if len(y_names) > 1:
                name = "values"
            else:
                name = y_names[0]
            ax.set(
                xlabel=x_name,
                ylabel=name,
            )
            ax.legend()
            ax.set_xticks(ax.get_xticks())
            ax.set_xticklabels(
                ax.get_xticklabels(),
                rotation=45,
                horizontalalignment="right",
            )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
            fig.tight_layout()

            return _figure_to_image(fig)

    # ------------------------------------------------------------------------------------------------------------------
    # Plots for all columns
    # ------------------------------------------------------------------------------------------------------------------

    def correlation_heatmap(self, *, theme: Literal["dark", "light"] = "light") -> Image:
        """
        Plot a correlation heatmap for all numerical columns of this `Table`.

        Parameters
        ----------
        theme:
            The color theme of the plot. Default is "light".

        Returns
        -------
        plot:
            The plot as an image.

        Examples
        --------
        >>> from safeds.data.tabular.containers import Table
        >>> table = Table({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
        >>> image = table.plot.correlation_heatmap()
        """
        import matplotlib.pyplot as plt
        import numpy as np

        style = "dark_background" if theme == "dark" else "default"
        with plt.style.context(style):
            if theme == "dark":
                plt.rcParams.update(
                    {
                        "text.color": "white",
                        "axes.labelcolor": "white",
                        "axes.edgecolor": "white",
                        "xtick.color": "white",
                        "ytick.color": "white",
                    },
                )

            only_numerical = self._table.remove_non_numeric_columns()._data_frame.fill_null(0)

            if self._table.row_count == 0:
                warnings.warn(
                    "An empty table has been used. A correlation heatmap on an empty table will show nothing.",
                    stacklevel=2,
                )

            with warnings.catch_warnings():
                warnings.filterwarnings(
                    "ignore",
                    message=(
                        "Attempting to set identical low and high (xlims|ylims) makes transformation singular;"
                        " automatically expanding."
                    ),
                )

                fig, ax = plt.subplots()
                heatmap = plt.imshow(
                    only_numerical.corr().to_numpy(),
                    vmin=-1,
                    vmax=1,
                    cmap="coolwarm",
                )
                ax.set_xticks(
                    np.arange(len(only_numerical.columns)),
                    rotation="vertical",
                    labels=only_numerical.columns,
                )
                ax.set_yticks(np.arange(len(only_numerical.columns)), labels=only_numerical.columns)
                fig.colorbar(heatmap)

                plt.tight_layout()

            return _figure_to_image(fig)

box_plots

Create a box plot for every numerical column.

Parameters:

Name Type Description Default
theme Literal['dark', 'light']

The color theme of the plot. Default is "light".

'light'

Returns:

Name Type Description
plot Image

The box plot(s) as an image.

Raises:

Type Description
NonNumericColumnError

If the table contains only non-numerical columns.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table({"a":[1, 2], "b": [3, 42]})
>>> image = table.plot.box_plots()
Source code in src/safeds/data/tabular/plotting/_table_plotter.py
def box_plots(self, *, theme: Literal["dark", "light"] = "light") -> Image:
    """
    Create a box plot for every numerical column.

    Parameters
    ----------
    theme:
        The color theme of the plot. Default is "light".

    Returns
    -------
    plot:
        The box plot(s) as an image.

    Raises
    ------
    NonNumericColumnError
        If the table contains only non-numerical columns.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table({"a":[1, 2], "b": [3, 42]})
    >>> image = table.plot.box_plots()
    """
    numerical_table = self._table.remove_non_numeric_columns()
    if numerical_table.column_count == 0:
        raise NonNumericColumnError("This table contains only non-numerical columns.")
    from math import ceil

    import matplotlib.pyplot as plt

    style = "dark_background" if theme == "dark" else "default"
    with plt.style.context(style):
        if theme == "dark":
            plt.rcParams.update(
                {
                    "text.color": "white",
                    "axes.labelcolor": "white",
                    "axes.edgecolor": "white",
                    "xtick.color": "white",
                    "ytick.color": "white",
                },
            )
        columns = numerical_table.to_columns()
        columns = [column._series.drop_nulls() for column in columns]
        max_width = 3
        number_of_columns = len(columns) if len(columns) <= max_width else max_width
        number_of_rows = ceil(len(columns) / number_of_columns)

        fig, axs = plt.subplots(nrows=number_of_rows, ncols=number_of_columns)
        line = 0
        for i, column in enumerate(columns):
            if i % number_of_columns == 0 and i != 0:
                line += 1

            if number_of_columns == 1:
                axs.boxplot(
                    column,
                    patch_artist=True,
                    tick_labels=[numerical_table.column_names[i]],
                )
                break

            if number_of_rows == 1:
                axs[i].boxplot(
                    column,
                    patch_artist=True,
                    tick_labels=[numerical_table.column_names[i]],
                )

            else:
                axs[line, i % number_of_columns].boxplot(
                    column,
                    patch_artist=True,
                    tick_labels=[numerical_table.column_names[i]],
                )

        # removes unused ax indices, so there wont be empty plots
        last_filled_ax_index = len(columns) % number_of_columns
        for i in range(last_filled_ax_index, number_of_columns):
            if number_of_rows != 1 and last_filled_ax_index != 0:
                fig.delaxes(axs[number_of_rows - 1, i])

        fig.tight_layout()
        return _figure_to_image(fig)

correlation_heatmap

Plot a correlation heatmap for all numerical columns of this Table.

Parameters:

Name Type Description Default
theme Literal['dark', 'light']

The color theme of the plot. Default is "light".

'light'

Returns:

Name Type Description
plot Image

The plot as an image.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
>>> image = table.plot.correlation_heatmap()
Source code in src/safeds/data/tabular/plotting/_table_plotter.py
def correlation_heatmap(self, *, theme: Literal["dark", "light"] = "light") -> Image:
    """
    Plot a correlation heatmap for all numerical columns of this `Table`.

    Parameters
    ----------
    theme:
        The color theme of the plot. Default is "light".

    Returns
    -------
    plot:
        The plot as an image.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table({"temperature": [10, 15, 20, 25, 30], "sales": [54, 74, 90, 206, 210]})
    >>> image = table.plot.correlation_heatmap()
    """
    import matplotlib.pyplot as plt
    import numpy as np

    style = "dark_background" if theme == "dark" else "default"
    with plt.style.context(style):
        if theme == "dark":
            plt.rcParams.update(
                {
                    "text.color": "white",
                    "axes.labelcolor": "white",
                    "axes.edgecolor": "white",
                    "xtick.color": "white",
                    "ytick.color": "white",
                },
            )

        only_numerical = self._table.remove_non_numeric_columns()._data_frame.fill_null(0)

        if self._table.row_count == 0:
            warnings.warn(
                "An empty table has been used. A correlation heatmap on an empty table will show nothing.",
                stacklevel=2,
            )

        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore",
                message=(
                    "Attempting to set identical low and high (xlims|ylims) makes transformation singular;"
                    " automatically expanding."
                ),
            )

            fig, ax = plt.subplots()
            heatmap = plt.imshow(
                only_numerical.corr().to_numpy(),
                vmin=-1,
                vmax=1,
                cmap="coolwarm",
            )
            ax.set_xticks(
                np.arange(len(only_numerical.columns)),
                rotation="vertical",
                labels=only_numerical.columns,
            )
            ax.set_yticks(np.arange(len(only_numerical.columns)), labels=only_numerical.columns)
            fig.colorbar(heatmap)

            plt.tight_layout()

        return _figure_to_image(fig)

histogram_2d

Create a 2D histogram for two columns in the table.

Parameters:

Name Type Description Default
x_name str

The name of the column to be plotted on the x-axis.

required
y_name str

The name of the column to be plotted on the y-axis.

required
x_max_bin_count int

The maximum number of bins to use in the histogram for the x-axis. Default is 10.

10
y_max_bin_count int

The maximum number of bins to use in the histogram for the y-axis. Default is 10.

10
theme Literal['dark', 'light']

The color theme of the plot. Default is "light".

'light'

Returns:

Name Type Description
plot Image

The plot as an image.

Raises:

Type Description
ColumnNotFoundError

If a column does not exist.

OutOfBoundsError:

If x_max_bin_count or y_max_bin_count is less than 1.

TypeError

If a column is not numeric.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table(
...     {
...         "a": [1, 2, 3, 4, 5],
...         "b": [2, 3, 4, 5, 6],
...     }
... )
>>> image = table.plot.histogram_2d("a", "b")
Source code in src/safeds/data/tabular/plotting/_table_plotter.py
def histogram_2d(
    self,
    x_name: str,
    y_name: str,
    *,
    x_max_bin_count: int = 10,
    y_max_bin_count: int = 10,
    theme: Literal["dark", "light"] = "light",
) -> Image:
    """
    Create a 2D histogram for two columns in the table.

    Parameters
    ----------
    x_name:
        The name of the column to be plotted on the x-axis.
    y_name:
        The name of the column to be plotted on the y-axis.
    x_max_bin_count:
        The maximum number of bins to use in the histogram for the x-axis. Default is 10.
    y_max_bin_count:
        The maximum number of bins to use in the histogram for the y-axis. Default is 10.
    theme:
        The color theme of the plot. Default is "light".

    Returns
    -------
    plot:
        The plot as an image.

    Raises
    ------
    ColumnNotFoundError
        If a column does not exist.
    OutOfBoundsError:
        If x_max_bin_count or y_max_bin_count is less than 1.
    TypeError
        If a column is not numeric.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table(
    ...     {
    ...         "a": [1, 2, 3, 4, 5],
    ...         "b": [2, 3, 4, 5, 6],
    ...     }
    ... )
    >>> image = table.plot.histogram_2d("a", "b")
    """
    _check_bounds("x_max_bin_count", x_max_bin_count, lower_bound=_ClosedBound(1))
    _check_bounds("y_max_bin_count", y_max_bin_count, lower_bound=_ClosedBound(1))
    _plot_validation(self._table, x_name, [y_name])

    import matplotlib.pyplot as plt

    if theme == "dark":
        context = "dark_background"
    else:
        context = "default"

    with plt.style.context(context):
        fig, ax = plt.subplots()

        ax.hist2d(
            x=self._table.get_column(x_name)._series,
            y=self._table.get_column(y_name)._series,
            bins=(x_max_bin_count, y_max_bin_count),
        )
        ax.set_xlabel(x_name)
        ax.set_ylabel(y_name)
        ax.tick_params(
            axis="x",
            labelrotation=45,
        )

        fig.tight_layout()

        return _figure_to_image(fig)

histograms

Plot a histogram for every column.

Parameters:

Name Type Description Default
max_bin_count int

The maximum number of bins to use in the histogram. Default is 10.

10
theme Literal['dark', 'light']

The color theme of the plot. Default is "light".

'light'

Returns:

Name Type Description
plot Image

The plot as an image.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table({"a": [2, 3, 5, 1], "b": [54, 74, 90, 2014]})
>>> image = table.plot.histograms()
Source code in src/safeds/data/tabular/plotting/_table_plotter.py
def histograms(self, *, max_bin_count: int = 10, theme: Literal["dark", "light"] = "light") -> Image:
    """
    Plot a histogram for every column.

    Parameters
    ----------
    max_bin_count:
        The maximum number of bins to use in the histogram. Default is 10.
    theme:
        The color theme of the plot. Default is "light".

    Returns
    -------
    plot:
        The plot as an image.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table({"a": [2, 3, 5, 1], "b": [54, 74, 90, 2014]})
    >>> image = table.plot.histograms()
    """
    import matplotlib.pyplot as plt

    style = "dark_background" if theme == "dark" else "default"
    with plt.style.context(style):
        if theme == "dark":
            plt.rcParams.update(
                {
                    "text.color": "white",
                    "axes.labelcolor": "white",
                    "axes.edgecolor": "white",
                    "xtick.color": "white",
                    "ytick.color": "white",
                },
            )
        import polars as pl

        n_cols = min(3, self._table.column_count)
        n_rows = 1 + (self._table.column_count - 1) // n_cols

        if n_cols == 1 and n_rows == 1:
            fig, axs = plt.subplots(1, 1, tight_layout=True)
            one_col = True
        else:
            fig, axs = plt.subplots(n_rows, n_cols, tight_layout=True, figsize=(n_cols * 3, n_rows * 3))
            one_col = False

        col_names = self._table.column_names
        for col_name, ax in zip(col_names, axs.flatten() if not one_col else [axs], strict=False):
            column = self._table.get_column(col_name)
            distinct_values = column.get_distinct_values()

            ax.set_title(col_name)
            ax.set_xlabel("")
            ax.set_ylabel("")

            if column.type.is_numeric and len(distinct_values) > max_bin_count:
                min_val = (column.min() or 0) - 1e-6  # Otherwise the minimum value is not included in the first bin
                max_val = column.max() or 0
                bin_count = min(max_bin_count, len(distinct_values))
                bins = [
                    *(pl.Series(range(bin_count + 1)) / bin_count * (max_val - min_val) + min_val),
                ]

                bars = [f"{round((bins[i] + bins[i + 1]) / 2, 2)}" for i in range(len(bins) - 1)]
                hist = column._series.hist(bins=bins).get_column("count").to_numpy()

                ax.bar(bars, hist, edgecolor="black")
                ax.set_xticks(range(len(hist)), bars, rotation=45, horizontalalignment="right")
            else:
                value_counts = (
                    column._series.drop_nulls().value_counts().sort(column.name).slice(0, length=max_bin_count)
                )
                distinct_values = value_counts.get_column(column.name).cast(pl.String).to_numpy()
                hist = value_counts.get_column("count").to_numpy()
                ax.bar(distinct_values, hist, edgecolor="black")
                ax.set_xticks(
                    range(len(distinct_values)),
                    distinct_values,
                    rotation=45,
                    horizontalalignment="right",
                )

        for i in range(len(col_names), n_rows * n_cols):
            fig.delaxes(axs.flatten()[i])  # Remove empty subplots

        return _figure_to_image(fig)

line_plot

Create a line plot for two columns in the table.

Parameters:

Name Type Description Default
x_name str

The name of the column to be plotted on the x-axis.

required
y_names list[str]

The name(s) of the column(s) to be plotted on the y-axis.

required
show_confidence_interval bool

If the confidence interval is shown, per default True.

True
theme Literal['dark', 'light']

The color theme of the plot. Default is "light".

'light'

Returns:

Name Type Description
plot Image

The plot as an image.

Raises:

Type Description
ColumnNotFoundError

If a column does not exist.

TypeError

If a column is not numeric.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table(
...     {
...         "a": [1, 2, 3, 4, 5],
...         "b": [2, 3, 4, 5, 6],
...     }
... )
>>> image = table.plot.line_plot("a", ["b"])
Source code in src/safeds/data/tabular/plotting/_table_plotter.py
def line_plot(
    self,
    x_name: str,
    y_names: list[str],
    *,
    show_confidence_interval: bool = True,
    theme: Literal["dark", "light"] = "light",
) -> Image:
    """
    Create a line plot for two columns in the table.

    Parameters
    ----------
    x_name:
        The name of the column to be plotted on the x-axis.
    y_names:
        The name(s) of the column(s) to be plotted on the y-axis.
    show_confidence_interval:
        If the confidence interval is shown, per default True.
    theme:
        The color theme of the plot. Default is "light".

    Returns
    -------
    plot:
        The plot as an image.

    Raises
    ------
    ColumnNotFoundError
        If a column does not exist.
    TypeError
        If a column is not numeric.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table(
    ...     {
    ...         "a": [1, 2, 3, 4, 5],
    ...         "b": [2, 3, 4, 5, 6],
    ...     }
    ... )
    >>> image = table.plot.line_plot("a", ["b"])
    """
    _plot_validation(self._table, x_name, y_names)

    import matplotlib.pyplot as plt

    style = "dark_background" if theme == "dark" else "default"
    with plt.style.context(style):
        if theme == "dark":
            plt.rcParams.update(
                {
                    "text.color": "white",
                    "axes.labelcolor": "white",
                    "axes.edgecolor": "white",
                    "xtick.color": "white",
                    "ytick.color": "white",
                },
            )
        import polars as pl

        agg_list = []
        for name in y_names:
            agg_list.append(pl.col(name).mean().alias(f"{name}_mean"))
            agg_list.append(pl.count(name).alias(f"{name}_count"))
            agg_list.append(pl.std(name, ddof=0).alias(f"{name}_std"))
        grouped_lazy = self._table._lazy_frame.sort(x_name).group_by(x_name, maintain_order=True).agg(agg_list)
        grouped = _safe_collect_lazy_frame(grouped_lazy)

        x = grouped.get_column(x_name)
        y_s = []
        confidence_intervals = []
        for name in y_names:
            y_s.append(grouped.get_column(name + "_mean"))
            confidence_intervals.append(
                1.96 * grouped.get_column(name + "_std") / grouped.get_column(name + "_count").sqrt(),
            )

        fig, ax = plt.subplots()
        for name, y in zip(y_names, y_s, strict=False):
            ax.plot(x, y, label=name)

        if show_confidence_interval:
            for y, conf in zip(y_s, confidence_intervals, strict=False):
                ax.fill_between(
                    x,
                    y - conf,
                    y + conf,
                    color="lightblue",
                    alpha=0.15,
                )
        if len(y_names) > 1:
            name = "values"
        else:
            name = y_names[0]
        ax.set(
            xlabel=x_name,
            ylabel=name,
        )
        ax.legend()
        ax.set_xticks(ax.get_xticks())
        ax.set_xticklabels(
            ax.get_xticklabels(),
            rotation=45,
            horizontalalignment="right",
        )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
        fig.tight_layout()

        return _figure_to_image(fig)

moving_average_plot

Create a moving average plot for the y column and plot it by the x column in the table.

Parameters:

Name Type Description Default
x_name str

The name of the column to be plotted on the x-axis.

required
y_name str

The name of the column to be plotted on the y-axis.

required
window_size int

The size of the moving average window

required
theme Literal['dark', 'light']

The color theme of the plot. Default is "light".

'light'

Returns:

Name Type Description
plot Image

The plot as an image.

Raises:

Type Description
ColumnNotFoundError

If a column does not exist.

TypeError

If a column is not numeric.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table(
...     {
...         "a": [1, 2, 3, 4, 5],
...         "b": [2, 3, 4, 5, 6],
...     }
... )
>>> image = table.plot.moving_average_plot("a", "b", window_size = 2)
Source code in src/safeds/data/tabular/plotting/_table_plotter.py
def moving_average_plot(
    self,
    x_name: str,
    y_name: str,
    window_size: int,
    *,
    theme: Literal["dark", "light"] = "light",
) -> Image:
    """
    Create a moving average plot for the y column and plot it by the x column in the table.

    Parameters
    ----------
    x_name:
        The name of the column to be plotted on the x-axis.
    y_name:
        The name of the column to be plotted on the y-axis.
    window_size:
        The size of the moving average window
    theme:
        The color theme of the plot. Default is "light".

    Returns
    -------
    plot:
        The plot as an image.

    Raises
    ------
    ColumnNotFoundError
        If a column does not exist.
    TypeError
        If a column is not numeric.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table(
    ...     {
    ...         "a": [1, 2, 3, 4, 5],
    ...         "b": [2, 3, 4, 5, 6],
    ...     }
    ... )
    >>> image = table.plot.moving_average_plot("a", "b", window_size = 2)
    """
    import matplotlib.pyplot as plt

    style = "dark_background" if theme == "dark" else "default"
    with plt.style.context(style):
        if theme == "dark":
            plt.rcParams.update(
                {
                    "text.color": "white",
                    "axes.labelcolor": "white",
                    "axes.edgecolor": "white",
                    "xtick.color": "white",
                    "ytick.color": "white",
                },
            )
        import numpy as np
        import polars as pl

        _plot_validation(self._table, x_name, [y_name])
        for name in [x_name, y_name]:
            if self._table.get_column(name).missing_value_count() >= 1:
                raise ValueError(
                    f"there are missing values in column '{name}', use transformation to fill missing values "
                    f"or drop the missing values. For a moving average no missing values are allowed.",
                )

        # Calculate the moving average
        mean_col = pl.col(y_name).mean().alias(y_name)
        grouped_lazy = self._table._lazy_frame.sort(x_name).group_by(x_name, maintain_order=True).agg(mean_col)
        data = _safe_collect_lazy_frame(grouped_lazy)
        moving_average = data.select([pl.col(y_name).rolling_mean(window_size).alias("moving_average")])
        # set up the arrays for plotting
        y_data_with_nan = moving_average["moving_average"].to_numpy()
        nan_mask = ~np.isnan(y_data_with_nan)
        y_data = y_data_with_nan[nan_mask]
        x_data = data[x_name].to_numpy()[nan_mask]
        fig, ax = plt.subplots()
        ax.plot(x_data, y_data, label="moving average")
        ax.set(
            xlabel=x_name,
            ylabel=y_name,
        )
        ax.legend()
        if self._table.get_column_type(x_name).is_temporal and self._table.get_column(x_name).row_count < 9:
            ax.set_xticks(x_data)  # Set x-ticks to the x data points
        ax.set_xticks(ax.get_xticks())
        ax.set_xticklabels(
            ax.get_xticklabels(),
            rotation=45,
            horizontalalignment="right",
        )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
        fig.tight_layout()

        return _figure_to_image(fig)

scatter_plot

Create a scatter plot for two columns in the table.

Parameters:

Name Type Description Default
x_name str

The name of the column to be plotted on the x-axis.

required
y_names list[str]

The name(s) of the column(s) to be plotted on the y-axis.

required
theme Literal['dark', 'light']

The color theme of the plot. Default is "light".

'light'

Returns:

Name Type Description
plot Image

The plot as an image.

Raises:

Type Description
ColumnNotFoundError

If a column does not exist.

TypeError

If a column is not numeric.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table(
...     {
...         "a": [1, 2, 3, 4, 5],
...         "b": [2, 3, 4, 5, 6],
...     }
... )
>>> image = table.plot.scatter_plot("a", ["b"])
Source code in src/safeds/data/tabular/plotting/_table_plotter.py
def scatter_plot(self, x_name: str, y_names: list[str], *, theme: Literal["dark", "light"] = "light") -> Image:
    """
    Create a scatter plot for two columns in the table.

    Parameters
    ----------
    x_name:
        The name of the column to be plotted on the x-axis.
    y_names:
        The name(s) of the column(s) to be plotted on the y-axis.
    theme:
        The color theme of the plot. Default is "light".

    Returns
    -------
    plot:
        The plot as an image.

    Raises
    ------
    ColumnNotFoundError
        If a column does not exist.
    TypeError
        If a column is not numeric.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table(
    ...     {
    ...         "a": [1, 2, 3, 4, 5],
    ...         "b": [2, 3, 4, 5, 6],
    ...     }
    ... )
    >>> image = table.plot.scatter_plot("a", ["b"])
    """
    _plot_validation(self._table, x_name, y_names)

    import matplotlib.pyplot as plt

    style = "dark_background" if theme == "dark" else "default"
    with plt.style.context(style):
        if theme == "dark":
            plt.rcParams.update(
                {
                    "text.color": "white",
                    "axes.labelcolor": "white",
                    "axes.edgecolor": "white",
                    "xtick.color": "white",
                    "ytick.color": "white",
                },
            )
        fig, ax = plt.subplots()
        for y_name in y_names:
            ax.scatter(
                x=self._table.get_column(x_name)._series,
                y=self._table.get_column(y_name)._series,
                s=64,  # marker size
                linewidth=1,
                edgecolor="white",
                label=y_name,
            )
        if len(y_names) > 1:
            name = "values"
        else:
            name = y_names[0]
        ax.set(
            xlabel=x_name,
            ylabel=name,
        )
        ax.legend()
        ax.set_xticks(ax.get_xticks())
        ax.set_xticklabels(
            ax.get_xticklabels(),
            rotation=45,
            horizontalalignment="right",
        )  # rotate the labels of the x Axis to prevent the chance of overlapping of the labels
        fig.tight_layout()

        return _figure_to_image(fig)

violin_plots

Create a violin plot for every numerical column.

Parameters:

Name Type Description Default
theme Literal['dark', 'light']

The color theme of the plot. Default is "light".

'light'

Returns:

Name Type Description
plot Image

The violin plot(s) as an image.

Raises:

Type Description
NonNumericColumnError

If the table contains only non-numerical columns.

Examples:

>>> from safeds.data.tabular.containers import Table
>>> table = Table({"a": [1, 2], "b": [3, 42]})
>>> image = table.plot.violin_plots()
Source code in src/safeds/data/tabular/plotting/_table_plotter.py
def violin_plots(self, *, theme: Literal["dark", "light"] = "light") -> Image:
    """
    Create a violin plot for every numerical column.

    Parameters
    ----------
    theme:
        The color theme of the plot. Default is "light".

    Returns
    -------
    plot:
        The violin plot(s) as an image.

    Raises
    ------
    NonNumericColumnError
        If the table contains only non-numerical columns.

    Examples
    --------
    >>> from safeds.data.tabular.containers import Table
    >>> table = Table({"a": [1, 2], "b": [3, 42]})
    >>> image = table.plot.violin_plots()
    """
    numerical_table = self._table.remove_non_numeric_columns()
    if numerical_table.column_count == 0:
        raise NonNumericColumnError("This table contains only non-numerical columns.")
    from math import ceil

    import matplotlib.pyplot as plt

    style = "dark_background" if theme == "dark" else "default"
    with plt.style.context(style):
        if theme == "dark":
            plt.rcParams.update(
                {
                    "text.color": "white",
                    "axes.labelcolor": "white",
                    "axes.edgecolor": "white",
                    "xtick.color": "white",
                    "ytick.color": "white",
                    "grid.color": "gray",
                    "grid.linewidth": 0.5,
                },
            )
        else:
            plt.rcParams.update(
                {
                    "grid.linewidth": 0.5,
                },
            )

        columns = numerical_table.to_columns()
        columns = [column._series.drop_nulls() for column in columns]
        max_width = 3
        number_of_columns = len(columns) if len(columns) <= max_width else max_width
        number_of_rows = ceil(len(columns) / number_of_columns)

        fig, axs = plt.subplots(nrows=number_of_rows, ncols=number_of_columns)
        line = 0
        for i, column in enumerate(columns):
            data = column.to_list()

            if i % number_of_columns == 0 and i != 0:
                line += 1

            if number_of_columns == 1:
                axs.violinplot(
                    data,
                )
                axs.set_title(numerical_table.column_names[i])
                break

            if number_of_rows == 1:
                axs[i].violinplot(
                    data,
                )
                axs[i].set_title(numerical_table.column_names[i])

            else:
                axs[line, i % number_of_columns].violinplot(
                    data,
                )
                axs[line, i % number_of_columns].set_title(numerical_table.column_names[i])

        # removes unused ax indices, so there wont be empty plots
        last_filled_ax_index = len(columns) % number_of_columns
        for i in range(last_filled_ax_index, number_of_columns):
            if number_of_rows != 1 and last_filled_ax_index != 0:
                fig.delaxes(axs[number_of_rows - 1, i])

        fig.tight_layout()
        return _figure_to_image(fig)