Skip to content

Reference

HiResMode

Bases: Enum

Source code in .venv/lib/python3.10/site-packages/textual_hires_canvas/hires.py
 7
 8
 9
10
class HiResMode(enum.Enum):
    HALFBLOCK = enum.auto()
    QUADRANT = enum.auto()
    BRAILLE = enum.auto()

LegendLocation

Bases: Enum

An enum to specify the location of the legend in the plot widget.

Source code in src/textual_plot/plot_widget.py
60
61
62
63
64
65
66
class LegendLocation(enum.Enum):
    """An enum to specify the location of the legend in the plot widget."""

    TOPLEFT = enum.auto()
    TOPRIGHT = enum.auto()
    BOTTOMLEFT = enum.auto()
    BOTTOMRIGHT = enum.auto()

PlotWidget

Bases: Widget

A plot widget for Textual apps.

This widget supports high-resolution line and scatter plots, has nice ticks at 1, 2, 5, 10, 20, 50, etc. intervals and supports zooming and panning with your pointer device.

The following component classes can be used to style the widget:

Class Description
plot--axis Style of the axes (may be used to change the color).
plot--tick Style of the tick labels along the axes.
plot--label Style of axis labels.
Source code in src/textual_plot/plot_widget.py
 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
762
763
764
765
766
767
768
769
770
771
772
773
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
835
836
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
911
912
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
941
942
943
944
945
946
947
948
class PlotWidget(Widget, can_focus=True):
    """A plot widget for Textual apps.

    This widget supports high-resolution line and scatter plots, has nice ticks
    at 1, 2, 5, 10, 20, 50, etc. intervals and supports zooming and panning with
    your pointer device.

    The following component classes can be used to style the widget:

    | Class | Description |
    | :- | :- |
    | `plot--axis` | Style of the axes (may be used to change the color). |
    | `plot--tick` | Style of the tick labels along the axes. |
    | `plot--label` | Style of axis labels. |
    """

    @dataclass
    class ScaleChanged(Message):
        plot: "PlotWidget"
        x_min: float
        x_max: float
        y_min: float
        y_max: float

    COMPONENT_CLASSES = {"plot--axis", "plot--tick", "plot--label"}

    DEFAULT_CSS = """
        PlotWidget {
            layers: plot legend;

            &:focus > .plot--axis {
                color: $primary;
            }

            & > .plot--axis {
                color: $secondary;
            }

            & > .plot--tick {
                color: $secondary;
                text-style: bold;
            }

            & > .plot--label {
                color: $primary;
                text-style: bold italic;
            }

            Grid {
                layer: plot;
                grid-size: 2 3;

                #margin-top, #margin-bottom {
                    column-span: 2;
                }
            }

            #legend {
              layer: legend;
              width: auto;
              border: solid white;
              display: none;

              &.dragged {
                border: heavy yellow;
              }
            }
        }
    """

    BINDINGS = [("r", "reset_scales", "Reset scales")]

    margin_top = reactive(2)
    margin_bottom = reactive(3)
    margin_left = reactive(10)

    _datasets: list[DataSet]
    _labels: list[str]

    _user_x_min: float | None = None
    _user_x_max: float | None = None
    _user_y_min: float | None = None
    _user_y_max: float | None = None
    _auto_x_min: bool = True
    _auto_x_max: bool = True
    _auto_y_min: bool = True
    _auto_y_max: bool = True
    _x_min: float = 0.0
    _x_max: float = 1.0
    _y_min: float = 0.0
    _y_max: float = 1.0

    _x_ticks: Sequence[float] | None = None
    _y_ticks: Sequence[float] | None = None

    _scale_rectangle: Region = Region(0, 0, 0, 0)
    _legend_location: LegendLocation = LegendLocation.TOPRIGHT
    _legend_relative_offset: Offset = Offset(0, 0)

    _x_label: str = ""
    _y_label: str = ""

    _allow_pan_and_zoom: bool = True
    _is_dragging_legend: bool = False
    _needs_rerender: bool = False

    def __init__(
        self,
        name: str | None = None,
        id: str | None = None,
        classes: str | None = None,
        *,
        allow_pan_and_zoom: bool = True,
        invert_mouse_wheel: bool = False,
        disabled: bool = False,
    ) -> None:
        """Initializes the plot widget with basic widget parameters.

        Params:
            name: The name of the widget.
            id: The ID of the widget in the DOM.
            classes: The CSS classes for the widget.
            allow_pan_and_zoom: Whether to allow panning and zooming the plot.
                Defaults to True.
            invert_mouse_wheel: When set to True the zooming direction is inverted
                when scrolling in and out of the widget. Defaults to False.
            disabled: Whether the widget is disabled or not.
        """
        super().__init__(
            name=name,
            id=id,
            classes=classes,
            disabled=disabled,
        )
        self._datasets = []
        self._labels = []
        self._allow_pan_and_zoom = allow_pan_and_zoom
        self.invert_mouse_wheel = invert_mouse_wheel

    def compose(self) -> ComposeResult:
        with Grid():
            yield Canvas(1, 1, id="margin-top")
            yield Canvas(1, 1, id="margin-left")
            yield Canvas(1, 1, id="plot")
            yield Canvas(1, 1, id="margin-bottom")
        yield Legend(id="legend")

    def on_mount(self) -> None:
        self._update_margin_sizes()
        self.set_xlimits(None, None)
        self.set_ylimits(None, None)
        self.clear()

    @on(Focus)
    @on(Blur)
    def rerender(self) -> None:
        self.refresh(layout=True)

    def _on_canvas_resize(self, event: Canvas.Resize) -> None:
        if event.canvas.id == "plot":
            # The scale rectangle falls just inside the axis rectangle
            self._scale_rectangle = Region(
                1, 1, event.size.width - 2, event.size.height - 2
            )
        event.canvas.reset(size=event.size)
        self._position_legend()
        self.refresh(layout=True)

    def watch_margin_top(self) -> None:
        self._update_margin_sizes()

    def watch_margin_bottom(self) -> None:
        self._update_margin_sizes()

    def watch_margin_left(self) -> None:
        self._update_margin_sizes()

    def _update_margin_sizes(self) -> None:
        """Update grid layout taking plot margins into account."""
        grid = self.query_one(Grid)
        grid.styles.grid_columns = f"{self.margin_left} 1fr"
        grid.styles.grid_rows = f"{self.margin_top} 1fr {self.margin_bottom}"

    def clear(self) -> None:
        """Clear the plot canvas."""
        self._datasets = []
        self._labels = []
        self.refresh(layout=True)

    def plot(
        self,
        x: ArrayLike,
        y: ArrayLike,
        line_style: str = "white",
        hires_mode: HiResMode | None = None,
        label: str | None = None,
    ) -> None:
        """Graph dataset using a line plot.

        If you supply hires_mode, the dataset will be plotted using one of the
        available high-resolution modes like 1x2, 2x2 or 2x8 pixel-per-cell
        characters.

        Args:
            x: An ArrayLike with the data values for the horizontal axis.
            y: An ArrayLike with the data values for the vertical axis.
            line_style: A string with the style of the line. Defaults to
                "white".
            hires_mode: A HiResMode enum or None to plot with full-height
                blocks. Defaults to None.
            label: A string with the label for the dataset. Defaults to None.
        """
        x, y = drop_nans_and_infs(np.array(x), np.array(y))
        self._datasets.append(
            LinePlot(
                x=x,
                y=y,
                line_style=line_style,
                hires_mode=hires_mode,
            )
        )
        self._labels.append(label or "")
        self.refresh(layout=True)

    def scatter(
        self,
        x: ArrayLike,
        y: ArrayLike,
        marker: str = "o",
        marker_style: str = "white",
        hires_mode: HiResMode | None = None,
        label: str | None = None,
    ) -> None:
        """Graph dataset using a scatter plot.

        If you supply hires_mode, the dataset will be plotted using one of the
        available high-resolution modes like 1x2, 2x2 or 2x8 pixel-per-cell
        characters.

        Args:
            x: An ArrayLike with the data values for the horizontal axis.
            y: An ArrayLike with the data values for the vertical axis.
            marker: A string with the character to print as the marker.
            marker_style: A string with the style of the marker. Defaults to
                "white".
            hires_mode: A HiResMode enum or None to plot with the supplied
                marker. Defaults to None.
            label: A string with the label for the dataset. Defaults to None.
        """
        x, y = drop_nans_and_infs(np.array(x), np.array(y))
        self._datasets.append(
            ScatterPlot(
                x=x,
                y=y,
                marker=marker,
                marker_style=marker_style,
                hires_mode=hires_mode,
            )
        )
        self._labels.append(label or "")
        self.refresh(layout=True)

    def set_xlimits(self, xmin: float | None = None, xmax: float | None = None) -> None:
        """Set the limits of the x axis.

        Args:
            xmin: A float with the minimum x value or None for autoscaling.
                Defaults to None.
            xmax: A float with the maximum x value or None for autoscaling.
                Defaults to None.
        """
        self._user_x_min = xmin
        self._user_x_max = xmax
        self._auto_x_min = xmin is None
        self._auto_x_max = xmax is None
        self._x_min = xmin if xmin is not None else 0.0
        self._x_max = xmax if xmax is not None else 1.0
        self.refresh(layout=True)

    def set_ylimits(self, ymin: float | None = None, ymax: float | None = None) -> None:
        """Set the limits of the y axis.

        Args:
            ymin: A float with the minimum y value or None for autoscaling.
                Defaults to None.
            ymax: A float with the maximum y value or None for autoscaling.
                Defaults to None.
        """
        self._user_y_min = ymin
        self._user_y_max = ymax
        self._auto_y_min = ymin is None
        self._auto_y_max = ymax is None
        self._y_min = ymin if ymin is not None else 0.0
        self._y_max = ymax if ymax is not None else 1.0
        self.refresh(layout=True)

    def set_xlabel(self, label: str) -> None:
        """Set a label for the x axis.

        Args:
            label: A string with the label text.
        """
        self._x_label = label

    def set_ylabel(self, label: str) -> None:
        """Set a label for the y axis.

        Args:
            label: A string with the label text.
        """
        self._y_label = label

    def set_xticks(self, ticks: Sequence[float] | None = None) -> None:
        """Set the x axis ticks.

        Use None for autoscaling, an empty list to hide the ticks.

        Args:
            ticks: An iterable with the tick values.
        """
        self._x_ticks = ticks

    def set_yticks(self, ticks: Sequence[float] | None = None) -> None:
        """Set the y axis ticks.

        Use None for autoscaling, an empty list to hide the ticks.

        Args:
            ticks: An iterable with the tick values.
        """
        self._y_ticks = ticks

    def show_legend(
        self,
        location: LegendLocation = LegendLocation.TOPRIGHT,
        is_visible: bool = True,
    ) -> None:
        """Show or hide the legend for the datasets in the plot.

        Args:
            is_visible: A boolean indicating whether to show the legend.
                Defaults to True.
        """
        self.query_one("#legend", Static).display = is_visible
        if not is_visible:
            return

        self._position_legend()

        legend_lines = []
        if isinstance(location, LegendLocation):
            self._legend_location = location
        else:
            raise TypeError(
                f"Expected LegendLocation, got {type(location).__name__} instead."
            )

        for label, dataset in zip(self._labels, self._datasets):
            if label is not None:
                if isinstance(dataset, ScatterPlot):
                    marker = (
                        dataset.marker
                        if dataset.hires_mode is None
                        else LEGEND_MARKER[dataset.hires_mode]
                    ).center(3)
                    style = dataset.marker_style
                elif isinstance(dataset, LinePlot):
                    marker = LEGEND_LINE[dataset.hires_mode]
                    style = dataset.line_style
                else:
                    # unsupported dataset type
                    continue
                text = Text(marker)
                text.stylize(style)
                text.append(f" {label}")
                legend_lines.append(text.markup)
        self.query_one("#legend", Static).update(
            Text.from_markup("\n".join(legend_lines))
        )

    def _position_legend(self) -> None:
        """Position the legend in the plot widget using absolute offsets.

        The position of the legend is calculated by checking the legend origin
        location (top left, bottom right, etc.) and an offset resulting from the
        user dragging the legend to another location. Then the nearest corner of
        the plot widget is determined and the legend is anchored to that corner
        and a new relative offset is determined. The end result is that the user
        can place the legend anywhere in the plot, but when the user resizes the
        plot the legend will stay fixed relative to the nearest corner.
        """

        position = (
            self._get_legend_origin_coordinates(self._legend_location)
            + self._legend_relative_offset
        )
        distances: dict[LegendLocation, float] = {
            location: self._get_legend_origin_coordinates(location).get_distance_to(
                position
            )
            for location in LegendLocation
        }
        nearest_location = min(distances, key=lambda loc: distances[loc])
        self._legend_location = nearest_location
        self._legend_relative_offset = position - self._get_legend_origin_coordinates(
            nearest_location
        )

        legend = self.query_one("#legend", Static)
        legend.offset = position

    def _get_legend_origin_coordinates(self, location: LegendLocation) -> Offset:
        """Calculate the (x, y) origin coordinates for positioning the legend.

        The coordinates are determined based on the legend's location (top-left,
        top-right, bottom-left, bottom-right), the size of the data rectangle,
        the length of the legend labels, and the margins and border spacing.
        User adjustments (dragging the legend to a different position) are _not_
        taken into account, but are applied later.

        Returns:
            A (x, y) tuple of ints representing the coordinates of the top-left
            corner of the legend within the plot widget.
        """
        canvas = self.query_one("#plot", Canvas)
        legend = self.query_one("#legend", Static)

        labels = [label for label in self._labels if label is not None]
        # markers and lines in the legend are 3 characters wide, plus a space, so 4
        max_length = 4 + max((len(s) for s in labels), default=0)

        if location in (LegendLocation.TOPLEFT, LegendLocation.BOTTOMLEFT):
            x0 = self.margin_left + 1
        else:
            # LegendLocation is TOPRIGHT or BOTTOMRIGHT
            x0 = self.margin_left + canvas.size.width - 1 - max_length
            # leave room for the border
            x0 -= legend.styles.border.spacing.left + legend.styles.border.spacing.right

        if location in (LegendLocation.TOPLEFT, LegendLocation.TOPRIGHT):
            y0 = self.margin_top + 1
        else:
            # LegendLocation is TOPRIGHT or BOTTOMRIGHT
            y0 = self.margin_top + canvas.size.height - 1 - len(labels)
            # leave room for the border
            y0 -= legend.styles.border.spacing.top + legend.styles.border.spacing.bottom
        return Offset(x0, y0)

    def refresh(
        self,
        *regions: Region,
        repaint: bool = True,
        layout: bool = False,
        recompose: bool = False,
    ) -> Self:
        """Refresh the widget."""
        if layout is True:
            self._needs_rerender = True
        return super().refresh(
            *regions, repaint=repaint, layout=layout, recompose=recompose
        )

    def render(self) -> RenderResult:
        if self._needs_rerender:
            self._needs_rerender = False
            self._render_plot()
        return ""

    def _render_plot(self) -> None:
        try:
            if (canvas := self.query_one("#plot", Canvas))._canvas_size is None:
                return
        except NoMatches:
            # Refresh is called before the widget is composed
            return

        # clear canvas
        canvas.reset()

        # determine axis limits
        if self._datasets:
            xs = [dataset.x for dataset in self._datasets]
            ys = [dataset.y for dataset in self._datasets]
            if self._auto_x_min:
                self._x_min = float(np.min([np.min(x) for x in xs]))
            if self._auto_x_max:
                self._x_max = float(np.max([np.max(x) for x in xs]))
            if self._auto_y_min:
                self._y_min = float(np.min([np.min(y) for y in ys]))
            if self._auto_y_max:
                self._y_max = float(np.max([np.max(y) for y in ys]))

            if self._x_min == self._x_max:
                self._x_min -= 1e-6
                self._x_max += 1e-6
            if self._y_min == self._y_max:
                self._y_min -= 1e-6
                self._y_max += 1e-6

        # render datasets
        for dataset in self._datasets:
            if isinstance(dataset, ScatterPlot):
                self._render_scatter_plot(dataset)
            elif isinstance(dataset, LinePlot):
                self._render_line_plot(dataset)

        # render axis, ticks and labels
        canvas.draw_rectangle_box(
            0,
            0,
            canvas.size.width - 1,
            canvas.size.height - 1,
            thickness=2,
            style=str(self.get_component_rich_style("plot--axis")),
        )
        self._render_x_ticks()
        self._render_y_ticks()
        self._render_x_label()
        self._render_y_label()

    def _render_scatter_plot(self, dataset: ScatterPlot) -> None:
        canvas = self.query_one("#plot", Canvas)
        if dataset.hires_mode:
            hires_pixels = [
                self.get_hires_pixel_from_coordinate(xi, yi)
                for xi, yi in zip(dataset.x, dataset.y)
            ]
            canvas.set_hires_pixels(
                hires_pixels, style=dataset.marker_style, hires_mode=dataset.hires_mode
            )
        else:
            pixels = [
                self.get_pixel_from_coordinate(xi, yi)
                for xi, yi in zip(dataset.x, dataset.y)
            ]
            for pixel in pixels:
                canvas.set_pixel(
                    *pixel, char=dataset.marker, style=dataset.marker_style
                )

    def _render_line_plot(self, dataset: LinePlot) -> None:
        canvas = self.query_one("#plot", Canvas)

        if dataset.hires_mode:
            hires_pixels = [
                self.get_hires_pixel_from_coordinate(xi, yi)
                for xi, yi in zip(dataset.x, dataset.y)
            ]
            coordinates = [
                (*hires_pixels[i - 1], *hires_pixels[i])
                for i in range(1, len(hires_pixels))
            ]
            canvas.draw_hires_lines(
                coordinates, style=dataset.line_style, hires_mode=dataset.hires_mode
            )
        else:
            pixels = [
                self.get_pixel_from_coordinate(xi, yi)
                for xi, yi in zip(dataset.x, dataset.y)
            ]
            for i in range(1, len(pixels)):
                canvas.draw_line(*pixels[i - 1], *pixels[i], style=dataset.line_style)

    def _render_x_ticks(self) -> None:
        canvas = self.query_one("#plot", Canvas)
        bottom_margin = self.query_one("#margin-bottom", Canvas)
        bottom_margin.reset()

        x_ticks: Sequence[float]
        if self._x_ticks is None:
            x_ticks, x_labels = self.get_ticks_between(self._x_min, self._x_max)
        else:
            x_ticks = self._x_ticks
            x_labels = self.get_labels_for_ticks(x_ticks)
        for tick, label in zip(x_ticks, x_labels):
            if tick < self._x_min or tick > self._x_max:
                continue
            align = TextAlign.CENTER
            # only interested in the x-coordinate, set y to 0.0
            x, _ = self.get_pixel_from_coordinate(tick, 0.0)
            if tick == self._x_min:
                x -= 1
            elif tick == self._x_max:
                align = TextAlign.RIGHT
            for y, quad in [
                # put ticks at top and bottom of scale rectangle
                (0, (2, 0, 0, 0)),
                (self._scale_rectangle.bottom, (0, 0, 2, 0)),
            ]:
                new_pixel = self.combine_quad_with_pixel(quad, canvas, x, y)
                canvas.set_pixel(
                    x,
                    y,
                    new_pixel,
                    style=str(self.get_component_rich_style("plot--axis")),
                )
            bottom_margin.write_text(
                x + self.margin_left,
                0,
                f"[{self.get_component_rich_style('plot--tick')}]{label}",
                align,
            )

    def _render_y_ticks(self) -> None:
        canvas = self.query_one("#plot", Canvas)
        left_margin = self.query_one("#margin-left", Canvas)
        left_margin.reset()

        y_ticks: Sequence[float]
        if self._y_ticks is None:
            y_ticks, y_labels = self.get_ticks_between(self._y_min, self._y_max)
        else:
            y_ticks = self._y_ticks
            y_labels = self.get_labels_for_ticks(y_ticks)
        # truncate y-labels to the left margin width
        y_labels = [label[: self.margin_left - 1] for label in y_labels]
        align = TextAlign.RIGHT
        for tick, label in zip(y_ticks, y_labels):
            if tick < self._y_min or tick > self._y_max:
                continue
            # only interested in the y-coordinate, set x to 0.0
            _, y = self.get_pixel_from_coordinate(0.0, tick)
            if tick == self._y_min:
                y += 1
            for x, quad in [
                # put ticks at left and right of scale rectangle
                (0, (0, 0, 0, 2)),
                (self._scale_rectangle.right, (0, 2, 0, 0)),
            ]:
                new_pixel = self.combine_quad_with_pixel(quad, canvas, x, y)
                canvas.set_pixel(
                    x,
                    y,
                    new_pixel,
                    style=str(self.get_component_rich_style("plot--axis")),
                )
            left_margin.write_text(
                self.margin_left - 2,
                y,
                f"[{self.get_component_rich_style('plot--tick')}]{label}",
                align,
            )

    def _render_x_label(self) -> None:
        canvas = self.query_one("#plot", Canvas)
        margin = self.query_one("#margin-bottom", Canvas)
        margin.write_text(
            canvas.size.width // 2 + self.margin_left,
            2,
            f"[{self.get_component_rich_style('plot--label')}]{self._x_label}",
            TextAlign.CENTER,
        )

    def _render_y_label(self) -> None:
        margin = self.query_one("#margin-top", Canvas)
        margin.write_text(
            self.margin_left - 2,
            0,
            f"[{self.get_component_rich_style('plot--label')}]{self._y_label}",
            TextAlign.CENTER,
        )

    def get_ticks_between(
        self, min_: float, max_: float, max_ticks: int = 8
    ) -> tuple[list[float], list[str]]:
        delta_x = max_ - min_
        tick_spacing = delta_x / 5
        power = floor(log10(tick_spacing))
        approx_interval = tick_spacing / 10**power
        intervals = np.array([1, 2, 5, 10])

        idx = intervals.searchsorted(approx_interval)
        interval = (intervals[idx - 1] if idx > 0 else intervals[0]) * 10**power
        if delta_x // interval > max_ticks:
            interval = intervals[idx] * 10**power
        ticks = [
            float(t)
            for t in np.arange(
                ceil(min_ / interval) * interval, max_ + interval / 2, interval
            )
        ]
        decimals = -min(0, power)
        tick_labels = self.get_labels_for_ticks(ticks, decimals)
        return ticks, tick_labels

    def get_labels_for_ticks(
        self, ticks: Sequence[float], decimals: int | None = None
    ) -> list[str]:
        """Generate formatted labels for given tick values.

        Args:
            ticks: A list of tick values to be formatted.
            decimals: The number of decimal places for formatting the tick values.

        Returns:
            A list of formatted tick labels as strings.
        """
        if not ticks:
            return []
        if decimals is None:
            if len(ticks) >= 2:
                power = floor(log10(ticks[1] - ticks[0]))
            else:
                power = 0
            decimals = -min(0, power)
        tick_labels = [f"{tick:.{decimals}f}" for tick in ticks]
        return tick_labels

    def combine_quad_with_pixel(
        self, quad: tuple[int, int, int, int], canvas: Canvas, x: int, y: int
    ) -> str:
        pixel = canvas.get_pixel(x, y)[0]
        for current_quad, v in BOX_CHARACTERS.items():
            if v == pixel:
                break
        new_quad = combine_quads(current_quad, quad)
        return BOX_CHARACTERS[new_quad]

    def get_pixel_from_coordinate(
        self, x: FloatScalar, y: FloatScalar
    ) -> tuple[int, int]:
        return map_coordinate_to_pixel(
            x,
            y,
            self._x_min,
            self._x_max,
            self._y_min,
            self._y_max,
            region=self._scale_rectangle,
        )

    def get_hires_pixel_from_coordinate(
        self, x: FloatScalar, y: FloatScalar
    ) -> tuple[FloatScalar, FloatScalar]:
        return map_coordinate_to_hires_pixel(
            x,
            y,
            self._x_min,
            self._x_max,
            self._y_min,
            self._y_max,
            region=self._scale_rectangle,
        )

    def get_coordinate_from_pixel(self, x: int, y: int) -> tuple[float, float]:
        return map_pixel_to_coordinate(
            x,
            y,
            self._x_min,
            self._x_max,
            self._y_min,
            self._y_max,
            region=self._scale_rectangle,
        )

    def _zoom(self, event: MouseScrollDown | MouseScrollUp, factor: float) -> None:
        if not self._allow_pan_and_zoom:
            return

        if self.invert_mouse_wheel:
            factor *= -1

        if (offset := event.get_content_offset(self)) is not None:
            widget, _ = self.screen.get_widget_at(event.screen_x, event.screen_y)
            canvas = self.query_one("#plot", Canvas)
            if widget.id == "margin-bottom":
                offset = event.screen_offset - self.screen.get_offset(canvas)
            x, y = self.get_coordinate_from_pixel(offset.x, offset.y)
            if widget.id in ("plot", "margin-bottom"):
                self._auto_x_min = False
                self._auto_x_max = False
                self._x_min = (self._x_min + factor * x) / (1 + factor)
                self._x_max = (self._x_max + factor * x) / (1 + factor)
            if widget.id in ("plot", "margin-left"):
                self._auto_y_min = False
                self._auto_y_max = False
                self._y_min = (self._y_min + factor * y) / (1 + factor)
                self._y_max = (self._y_max + factor * y) / (1 + factor)
            self.post_message(
                self.ScaleChanged(
                    self, self._x_min, self._x_max, self._y_min, self._y_max
                )
            )
            self.refresh(layout=True)

    @on(MouseScrollDown)
    def zoom_in(self, event: MouseScrollDown) -> None:
        event.stop()
        self._zoom(event, ZOOM_FACTOR)

    @on(MouseScrollUp)
    def zoom_out(self, event: MouseScrollUp) -> None:
        event.stop()
        self._zoom(event, -ZOOM_FACTOR)

    @on(MouseDown)
    def start_dragging_legend(self, event: MouseDown) -> None:
        widget, _ = self.screen.get_widget_at(event.screen_x, event.screen_y)
        if event.button == 1 and widget.id == "legend":
            self._is_dragging_legend = True
            widget.add_class("dragged")
            event.stop()

    @on(MouseUp)
    def stop_dragging_legend(self, event: MouseUp) -> None:
        if event.button == 1 and self._is_dragging_legend:
            self._is_dragging_legend = False
            self.query_one("#legend").remove_class("dragged")
            event.stop()

    @on(MouseMove)
    def drag_with_mouse(self, event: MouseMove) -> None:
        if not self._allow_pan_and_zoom:
            return
        if event.button == 0:
            # If no button is pressed, don't drag.
            return

        if self._is_dragging_legend:
            self._drag_legend(event)
        else:
            self._pan_plot(event)

    def _drag_legend(self, event: MouseMove) -> None:
        self._legend_relative_offset += event.delta
        self._position_legend()
        self.query_one("#legend").refresh(layout=True)

    def _pan_plot(self, event: MouseMove) -> None:
        x1, y1 = self.get_coordinate_from_pixel(1, 1)
        x2, y2 = self.get_coordinate_from_pixel(2, 2)
        dx, dy = x2 - x1, y1 - y2

        assert event.widget is not None
        if event.widget.id in ("plot", "margin-bottom"):
            self._auto_x_min = False
            self._auto_x_max = False
            self._x_min -= dx * event.delta_x
            self._x_max -= dx * event.delta_x
        if event.widget.id in ("plot", "margin-left"):
            self._auto_y_min = False
            self._auto_y_max = False
            self._y_min += dy * event.delta_y
            self._y_max += dy * event.delta_y
        self.post_message(
            self.ScaleChanged(self, self._x_min, self._x_max, self._y_min, self._y_max)
        )
        self.refresh(layout=True)

    def action_reset_scales(self) -> None:
        self.set_xlimits(self._user_x_min, self._user_x_max)
        self.set_ylimits(self._user_y_min, self._user_y_max)
        self.post_message(
            self.ScaleChanged(self, self._x_min, self._x_max, self._y_min, self._y_max)
        )
        self.refresh()

__init__(name=None, id=None, classes=None, *, allow_pan_and_zoom=True, invert_mouse_wheel=False, disabled=False)

Initializes the plot widget with basic widget parameters.

Parameters:

Name Type Description Default
name str | None

The name of the widget.

None
id str | None

The ID of the widget in the DOM.

None
classes str | None

The CSS classes for the widget.

None
allow_pan_and_zoom bool

Whether to allow panning and zooming the plot. Defaults to True.

True
invert_mouse_wheel bool

When set to True the zooming direction is inverted when scrolling in and out of the widget. Defaults to False.

False
disabled bool

Whether the widget is disabled or not.

False
Source code in src/textual_plot/plot_widget.py
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
def __init__(
    self,
    name: str | None = None,
    id: str | None = None,
    classes: str | None = None,
    *,
    allow_pan_and_zoom: bool = True,
    invert_mouse_wheel: bool = False,
    disabled: bool = False,
) -> None:
    """Initializes the plot widget with basic widget parameters.

    Params:
        name: The name of the widget.
        id: The ID of the widget in the DOM.
        classes: The CSS classes for the widget.
        allow_pan_and_zoom: Whether to allow panning and zooming the plot.
            Defaults to True.
        invert_mouse_wheel: When set to True the zooming direction is inverted
            when scrolling in and out of the widget. Defaults to False.
        disabled: Whether the widget is disabled or not.
    """
    super().__init__(
        name=name,
        id=id,
        classes=classes,
        disabled=disabled,
    )
    self._datasets = []
    self._labels = []
    self._allow_pan_and_zoom = allow_pan_and_zoom
    self.invert_mouse_wheel = invert_mouse_wheel

clear()

Clear the plot canvas.

Source code in src/textual_plot/plot_widget.py
276
277
278
279
280
def clear(self) -> None:
    """Clear the plot canvas."""
    self._datasets = []
    self._labels = []
    self.refresh(layout=True)

get_labels_for_ticks(ticks, decimals=None)

Generate formatted labels for given tick values.

Parameters:

Name Type Description Default
ticks Sequence[float]

A list of tick values to be formatted.

required
decimals int | None

The number of decimal places for formatting the tick values.

None

Returns:

Type Description
list[str]

A list of formatted tick labels as strings.

Source code in src/textual_plot/plot_widget.py
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
def get_labels_for_ticks(
    self, ticks: Sequence[float], decimals: int | None = None
) -> list[str]:
    """Generate formatted labels for given tick values.

    Args:
        ticks: A list of tick values to be formatted.
        decimals: The number of decimal places for formatting the tick values.

    Returns:
        A list of formatted tick labels as strings.
    """
    if not ticks:
        return []
    if decimals is None:
        if len(ticks) >= 2:
            power = floor(log10(ticks[1] - ticks[0]))
        else:
            power = 0
        decimals = -min(0, power)
    tick_labels = [f"{tick:.{decimals}f}" for tick in ticks]
    return tick_labels

plot(x, y, line_style='white', hires_mode=None, label=None)

Graph dataset using a line plot.

If you supply hires_mode, the dataset will be plotted using one of the available high-resolution modes like 1x2, 2x2 or 2x8 pixel-per-cell characters.

Parameters:

Name Type Description Default
x ArrayLike

An ArrayLike with the data values for the horizontal axis.

required
y ArrayLike

An ArrayLike with the data values for the vertical axis.

required
line_style str

A string with the style of the line. Defaults to "white".

'white'
hires_mode HiResMode | None

A HiResMode enum or None to plot with full-height blocks. Defaults to None.

None
label str | None

A string with the label for the dataset. Defaults to None.

None
Source code in src/textual_plot/plot_widget.py
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
def plot(
    self,
    x: ArrayLike,
    y: ArrayLike,
    line_style: str = "white",
    hires_mode: HiResMode | None = None,
    label: str | None = None,
) -> None:
    """Graph dataset using a line plot.

    If you supply hires_mode, the dataset will be plotted using one of the
    available high-resolution modes like 1x2, 2x2 or 2x8 pixel-per-cell
    characters.

    Args:
        x: An ArrayLike with the data values for the horizontal axis.
        y: An ArrayLike with the data values for the vertical axis.
        line_style: A string with the style of the line. Defaults to
            "white".
        hires_mode: A HiResMode enum or None to plot with full-height
            blocks. Defaults to None.
        label: A string with the label for the dataset. Defaults to None.
    """
    x, y = drop_nans_and_infs(np.array(x), np.array(y))
    self._datasets.append(
        LinePlot(
            x=x,
            y=y,
            line_style=line_style,
            hires_mode=hires_mode,
        )
    )
    self._labels.append(label or "")
    self.refresh(layout=True)

refresh(*regions, repaint=True, layout=False, recompose=False)

Refresh the widget.

Source code in src/textual_plot/plot_widget.py
541
542
543
544
545
546
547
548
549
550
551
552
553
def refresh(
    self,
    *regions: Region,
    repaint: bool = True,
    layout: bool = False,
    recompose: bool = False,
) -> Self:
    """Refresh the widget."""
    if layout is True:
        self._needs_rerender = True
    return super().refresh(
        *regions, repaint=repaint, layout=layout, recompose=recompose
    )

scatter(x, y, marker='o', marker_style='white', hires_mode=None, label=None)

Graph dataset using a scatter plot.

If you supply hires_mode, the dataset will be plotted using one of the available high-resolution modes like 1x2, 2x2 or 2x8 pixel-per-cell characters.

Parameters:

Name Type Description Default
x ArrayLike

An ArrayLike with the data values for the horizontal axis.

required
y ArrayLike

An ArrayLike with the data values for the vertical axis.

required
marker str

A string with the character to print as the marker.

'o'
marker_style str

A string with the style of the marker. Defaults to "white".

'white'
hires_mode HiResMode | None

A HiResMode enum or None to plot with the supplied marker. Defaults to None.

None
label str | None

A string with the label for the dataset. Defaults to None.

None
Source code in src/textual_plot/plot_widget.py
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
def scatter(
    self,
    x: ArrayLike,
    y: ArrayLike,
    marker: str = "o",
    marker_style: str = "white",
    hires_mode: HiResMode | None = None,
    label: str | None = None,
) -> None:
    """Graph dataset using a scatter plot.

    If you supply hires_mode, the dataset will be plotted using one of the
    available high-resolution modes like 1x2, 2x2 or 2x8 pixel-per-cell
    characters.

    Args:
        x: An ArrayLike with the data values for the horizontal axis.
        y: An ArrayLike with the data values for the vertical axis.
        marker: A string with the character to print as the marker.
        marker_style: A string with the style of the marker. Defaults to
            "white".
        hires_mode: A HiResMode enum or None to plot with the supplied
            marker. Defaults to None.
        label: A string with the label for the dataset. Defaults to None.
    """
    x, y = drop_nans_and_infs(np.array(x), np.array(y))
    self._datasets.append(
        ScatterPlot(
            x=x,
            y=y,
            marker=marker,
            marker_style=marker_style,
            hires_mode=hires_mode,
        )
    )
    self._labels.append(label or "")
    self.refresh(layout=True)

set_xlabel(label)

Set a label for the x axis.

Parameters:

Name Type Description Default
label str

A string with the label text.

required
Source code in src/textual_plot/plot_widget.py
389
390
391
392
393
394
395
def set_xlabel(self, label: str) -> None:
    """Set a label for the x axis.

    Args:
        label: A string with the label text.
    """
    self._x_label = label

set_xlimits(xmin=None, xmax=None)

Set the limits of the x axis.

Parameters:

Name Type Description Default
xmin float | None

A float with the minimum x value or None for autoscaling. Defaults to None.

None
xmax float | None

A float with the maximum x value or None for autoscaling. Defaults to None.

None
Source code in src/textual_plot/plot_widget.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
def set_xlimits(self, xmin: float | None = None, xmax: float | None = None) -> None:
    """Set the limits of the x axis.

    Args:
        xmin: A float with the minimum x value or None for autoscaling.
            Defaults to None.
        xmax: A float with the maximum x value or None for autoscaling.
            Defaults to None.
    """
    self._user_x_min = xmin
    self._user_x_max = xmax
    self._auto_x_min = xmin is None
    self._auto_x_max = xmax is None
    self._x_min = xmin if xmin is not None else 0.0
    self._x_max = xmax if xmax is not None else 1.0
    self.refresh(layout=True)

set_xticks(ticks=None)

Set the x axis ticks.

Use None for autoscaling, an empty list to hide the ticks.

Parameters:

Name Type Description Default
ticks Sequence[float] | None

An iterable with the tick values.

None
Source code in src/textual_plot/plot_widget.py
405
406
407
408
409
410
411
412
413
def set_xticks(self, ticks: Sequence[float] | None = None) -> None:
    """Set the x axis ticks.

    Use None for autoscaling, an empty list to hide the ticks.

    Args:
        ticks: An iterable with the tick values.
    """
    self._x_ticks = ticks

set_ylabel(label)

Set a label for the y axis.

Parameters:

Name Type Description Default
label str

A string with the label text.

required
Source code in src/textual_plot/plot_widget.py
397
398
399
400
401
402
403
def set_ylabel(self, label: str) -> None:
    """Set a label for the y axis.

    Args:
        label: A string with the label text.
    """
    self._y_label = label

set_ylimits(ymin=None, ymax=None)

Set the limits of the y axis.

Parameters:

Name Type Description Default
ymin float | None

A float with the minimum y value or None for autoscaling. Defaults to None.

None
ymax float | None

A float with the maximum y value or None for autoscaling. Defaults to None.

None
Source code in src/textual_plot/plot_widget.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
def set_ylimits(self, ymin: float | None = None, ymax: float | None = None) -> None:
    """Set the limits of the y axis.

    Args:
        ymin: A float with the minimum y value or None for autoscaling.
            Defaults to None.
        ymax: A float with the maximum y value or None for autoscaling.
            Defaults to None.
    """
    self._user_y_min = ymin
    self._user_y_max = ymax
    self._auto_y_min = ymin is None
    self._auto_y_max = ymax is None
    self._y_min = ymin if ymin is not None else 0.0
    self._y_max = ymax if ymax is not None else 1.0
    self.refresh(layout=True)

set_yticks(ticks=None)

Set the y axis ticks.

Use None for autoscaling, an empty list to hide the ticks.

Parameters:

Name Type Description Default
ticks Sequence[float] | None

An iterable with the tick values.

None
Source code in src/textual_plot/plot_widget.py
415
416
417
418
419
420
421
422
423
def set_yticks(self, ticks: Sequence[float] | None = None) -> None:
    """Set the y axis ticks.

    Use None for autoscaling, an empty list to hide the ticks.

    Args:
        ticks: An iterable with the tick values.
    """
    self._y_ticks = ticks

show_legend(location=LegendLocation.TOPRIGHT, is_visible=True)

Show or hide the legend for the datasets in the plot.

Parameters:

Name Type Description Default
is_visible bool

A boolean indicating whether to show the legend. Defaults to True.

True
Source code in src/textual_plot/plot_widget.py
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
def show_legend(
    self,
    location: LegendLocation = LegendLocation.TOPRIGHT,
    is_visible: bool = True,
) -> None:
    """Show or hide the legend for the datasets in the plot.

    Args:
        is_visible: A boolean indicating whether to show the legend.
            Defaults to True.
    """
    self.query_one("#legend", Static).display = is_visible
    if not is_visible:
        return

    self._position_legend()

    legend_lines = []
    if isinstance(location, LegendLocation):
        self._legend_location = location
    else:
        raise TypeError(
            f"Expected LegendLocation, got {type(location).__name__} instead."
        )

    for label, dataset in zip(self._labels, self._datasets):
        if label is not None:
            if isinstance(dataset, ScatterPlot):
                marker = (
                    dataset.marker
                    if dataset.hires_mode is None
                    else LEGEND_MARKER[dataset.hires_mode]
                ).center(3)
                style = dataset.marker_style
            elif isinstance(dataset, LinePlot):
                marker = LEGEND_LINE[dataset.hires_mode]
                style = dataset.line_style
            else:
                # unsupported dataset type
                continue
            text = Text(marker)
            text.stylize(style)
            text.append(f" {label}")
            legend_lines.append(text.markup)
    self.query_one("#legend", Static).update(
        Text.from_markup("\n".join(legend_lines))
    )