Skip to content

Interactive Controls

H.P. Gansevoort edited this page Nov 27, 2026 · 17 revisions

Interactive Controls

Native chart controls for Avalonia 12, Uno Platform (WinUI 3), WPF and .NET MAUI with 15 interaction modifiers. They need no browser, no WebView and no SignalR.

All listed interactions are enabled by one switch: FigureBuilder.WithBrowserInteraction() in browser hosts, or the IsInteractive property of the Avalonia, Uno, WPF and MAUI controls in native hosts. The library decides which scripts and handlers to wire. There is no per-feature toggle.

Interaction Gestures (v1.4.1, legend drag added in v1.7.2, stacked Y axes added in v1.23.0)

Gesture Modifier What it does
Left drag (none) Pan the axes. A chart that scales itself is pinned at the range on screen first; a timeline pans along time only; axes linked by ShareX move together
Scroll wheel (none) Zoom in or out around the pointer (along time only on a timeline, and together on axes linked by ShareX)
Right drag (on 3D axes) Rotate the 3D camera
Ctrl + left drag Rectangle zoom: draw a box and release to zoom
Shift + left drag Brush select: draw a rectangle, which fires an event
Alt + left drag Span select: selects a horizontal X range
Double-click Reset the axes to auto-scale
Arrow keys (on 3D axes) Rotate the camera by ±5° in azimuth or elevation
Home (on 3D axes) Reset the camera to the default (30°, -60°)
Home / Escape (on 2D axes) Reset the axes to the view the chart had before an interaction first moved it, however many repaints and zooms came between
Click legend item Toggle the series' visibility (Enter or Space from the keyboard); a series with several legend entries, such as the named layers of a stack plot, is toggled whole, and all its entries dim together
Press-and-hold legend item, drag, release (browser only) Reposition the legend group in an SVG made with WithBrowserInteraction(); the move stays in the page, so a server re-render loses it. The native controls do not move the legend
Click a data point Pin an annotation to it, and raise DataPointClicked with the point
Hover Show a tooltip for the nearest point, and say which point it is
Mouse move (passive) Draw crosshair lines at the data coordinates

A finger on a MAUI chart does the same through one TouchGestureTranslator. IsInteractive is off by default there, so a chart on a scrolling page does not take the drag meant to scroll it.

Touch What it does
One-finger drag What DragAction says: Pan (the default), RectangleZoom, BrushSelect, SpanSelect or Rotate. A drag in progress keeps the action it began with
Pinch Zoom, in whole notches of the wheel: 0.85 of the range in, 1/0.85 out, as matplotlib's wheel
Tap A click: a data point, a legend entry
Double tap Home
Hover The tooltip of the nearest point, where the device has a pointer

Pan, zoom, rectangle zoom and reset move every Y axis of the chart, not only the primary one: the primary axis and each axis added with WithAddRightYAxis or WithAddLeftYAxis, however many there are, gets its own proportional share of the same drag or wheel event, whether a server answers the gesture or a native control does.

An event that cannot be applied costs the chart only that event. One that names a subplot the figure does not have (a negative index, one past the last subplot, any index on a figure with no subplots) is dropped instead of throwing, for every event the library ships: zoom, reset, rectangle zoom, pan, legend toggle, 3-D rotation and the add and remove events of the drawing tools. An event that fails in any other way while a live chart is served over SignalR, such as a crafted one or a handler of your own that throws, is lost on its own and no longer ends that chart's session for good, as it used to: the next events are applied and published as usual.

Quick start

Avalonia

dotnet add package MatPlotLibNet.Avalonia
<local:MplChartControl Figure="{Binding MyFigure}" IsInteractive="True" />

Uno Platform

dotnet add package MatPlotLibNet.Uno
<local:MplChartElement Figure="{x:Bind MyFigure}" IsInteractive="True" />

Architecture

The managed interaction layer lives entirely in the zero-dependency core package (MatPlotLibNet). Platform controls translate native pointer and keyboard events into neutral PointerInputArgs, ScrollInputArgs and KeyInputArgs records, then delegate to InteractionController.

Native event (Avalonia / Uno / WinUI)
    │
    ▼
the control's own input reading         ← platform-specific, a few lines per event
    │
    ▼
InteractionController                    ← core, composes 15 modifiers
    │
    ▼
IInteractionModifier (first match wins)  ← core, one per gesture
    │
    ▼
FigureInteractionEvent                   ← core, same hierarchy as SignalR path
    │
    ▼
evt.ApplyTo(figure)  →  InvalidateVisual()   ← local mode (default)
    or
Action<FigureInteractionEvent> sink           ← server mode (opt-in)

One host for every control

The four controls derive from four different base classes, so what they share is an object they compose, InteractionHost. It owns the InteractionController and keeps it aimed at the figure the control is showing: the control forwards its input, and hands over the figure and the layout of every paint. The first paint of a figure builds a controller for it, a paint of another figure builds a new one, so a gesture acts on the figure now on screen, and a repaint of the same figure only replaces the layout, so a gesture that is going on keeps going. That is also why Home goes back to where the reader started: the figure remembers the view each axes had before an interaction first moved it, and the host's repaints do not touch that memory.

The streaming controls of WPF, Avalonia, Uno and MAUI take IsInteractive too. A streaming chart the reader has moved stays where they put it while data keeps arriving, until Home hands it back to the scale mode that follows the data. What a streaming control does with its figure (listen to it, let go of it, set the limits from the data before each draw on the control's own thread) is written once in the core package and composed by all four, which differ only in how they reach their thread and ask to be drawn.

Controller

InteractionController is the central dispatcher. It has two factory methods:

Factory Mode Use case
CreateLocal(figure, layout) Local In-process mutation; the control repaints automatically
Create(figure, layout, sink) Custom Forwards events to SignalR, to logging, or to any Action<FigureInteractionEvent>

Modifiers (priority order)

# Modifier Gesture Event
1 LegendToggleModifier Click on a legend item LegendToggleEvent
2 ResetModifier Double-click, or Home / Escape ResetEvent
3 Rotate3DModifier Right-drag, arrow keys or Home on 3D axes Rotate3DEvent
4 RectangleZoomModifier Ctrl + left-drag RectangleZoomEvent
5 BrushSelectModifier Shift + left-drag BrushSelectEvent
6 SpanSelectModifier Alt + left-drag SpanSelectEvent
7 TrendlineDrawingModifier Left clicks while the toolbar's trendline tool is active AddTrendlineEvent
8 LevelDrawingModifier Left click while the toolbar's level tool is active AddHorizontalLevelEvent
9 FibonacciDrawingModifier Left clicks while the toolbar's Fibonacci tool is active AddFibonacciRetracementEvent
10 DrawingToolSelectionModifier Delete on a selected drawing RemoveDrawingToolEvent
11 DataCursorModifier Left click within ten pixels of a data point DataCursorEvent
12 PanModifier Left-drag PanEvent
13 ZoomModifier Scroll wheel ZoomEvent
14 CrosshairModifier Every mouse move — (draws the crosshair in the control)
15 HoverModifier Mouse move HoverEvent

A press, a scroll or a key goes to the first modifier in this order that claims it, and only to that one: a click that misses every data point falls through the data cursor to the pan. The crosshair and the hover are passive and see every move, whichever modifier holds the drag.

ChartLayout

ChartLayout converts pixel positions to data-space coordinates. A native control builds it from the layout its paint returns, laid out in the same pass that draws (for a figure drawn elsewhere, ChartRenderer.ComputeLayout(figure, context) gives the same layout), and it converts with the range and the scale the renderer draws: an axes that scales itself, explicit limits, log and symlog axes and an axis with breaks all read the value under the pointer in data units. Past a break the pointer reads the value drawn there, not one short by the gap the break cuts out; the one pixel where a break is cut reads where the break begins.

Method Purpose
HitTestAxes(pixelX, pixelY) Finds which subplot contains the point
PixelToData(pixelX, pixelY, axesIndex) Converts pixel coordinates to data coordinates
GetDataRange(axesIndex) Returns the range the axes shows (XMin, XMax, YMin, YMax), in data units
HitTestLegendItem(pixelX, pixelY, axesIndex) Finds which legend entry was clicked

Event hierarchy

FigureInteractionEvent (abstract)
├── AxisRangeEvent (abstract, sealed ApplyTo)
│   ├── ZoomEvent                     ← sets axis limits
│   ├── RectangleZoomEvent            ← sets axis limits to the drawn box
│   └── ResetEvent                    ← restores original limits
├── PanEvent                          ← translates axis limits by delta
├── LegendToggleEvent                 ← flips series visibility
├── Rotate3DEvent                     ← turns the 3D camera
├── AddTrendlineEvent                 ← adds a drawn trendline
├── AddHorizontalLevelEvent           ← adds a drawn level
├── AddFibonacciRetracementEvent      ← adds a drawn retracement
├── RemoveDrawingToolEvent            ← removes a drawing
└── FigureNotificationEvent (abstract, sealed no-op ApplyTo)
    ├── BrushSelectEvent              ← rectangular selection (fire-and-forget)
    ├── SpanSelectEvent               ← X-range selection (fire-and-forget)
    ├── DataCursorEvent               ← a clicked data point (fire-and-forget)
    └── HoverEvent                    ← data-space position (fire-and-forget)

One handler for everything the reader does

A control used to give your application the click on a data point and nothing else. ChartEventHandler takes an IChartEventHandler, the same interface a server session takes (ChartSessionOptions.Handle), and tells it of every gesture once the figure (or the server sink) has taken it: a zoom, a pan, a legend toggle, a reset, a brush. A brush over points that carry RowKeys is also said as a RowSelectionEvent, with the keys of the rows it covers. The handler runs inline, so the next gesture waits for it; a handler that throws costs its own event only, and ChartEventHandlerFaulted reports it:

using MatPlotLibNet;
using MatPlotLibNet.Avalonia;
using MatPlotLibNet.Interaction;

var chart = new MplChartControl
{
    Figure = Plt.Create().Plot([1.0, 2.0, 3.0], [2.0, 4.0, 3.0]).Build(),
    IsInteractive = true,
    ChartEventHandler = new GestureLog(),
};
chart.ChartEventHandlerFaulted += failure => Console.WriteLine($"The handler failed: {failure.Message}");

sealed class GestureLog : IChartEventHandler
{
    public ValueTask OnEventAsync(FigureInteractionEvent evt, ChartEventContext context)
    {
        Console.WriteLine($"{evt.GetType().Name} on {evt.ChartId}");
        return ValueTask.CompletedTask;
    }
}

The WPF, Uno and MAUI controls, and the streaming controls of the first three, carry the same two members. The context names the viewer only for an event that came over a server connection; on a native control it is empty.

Custom event sink (server mode)

For SignalR-connected charts, construct the controller with a custom sink. SignalREventSink.Create sends each event to the ChartHub method that takes it (OnZoom, OnPan, OnReset, and so on):

using MatPlotLibNet;
using MatPlotLibNet.Interaction;
using MatPlotLibNet.Rendering.Svg;
using Microsoft.AspNetCore.SignalR.Client;

var hubConnection = new HubConnectionBuilder()
    .WithUrl("https://localhost:5001/charts-hub")
    .Build();
await hubConnection.StartAsync();

var figure = Plt.Create()
    .WithServerInteraction("sales", i => i.All())
    .Plot([1.0, 2.0, 3.0], [2.0, 4.0, 3.0])
    .Build();

// The layout a control computes after each render pass.
var layout = ChartLayout.Create(figure, ChartRendererDefault.Current.ComputeLayout(figure, new SvgRenderContext()));

var ctrl = InteractionController.Create(figure, layout,
    SignalREventSink.Create((method, payload) => hubConnection.SendAsync(method, payload)));

Or use the built-in extension method on the control, which builds that sink for you:

using MatPlotLibNet.Avalonia;

var chartControl = new MplChartControl { Figure = figure };
chartControl.WithServerInteraction((method, payload) => hubConnection.SendAsync(method, payload));

Rubber-band visual

During a Shift + left drag, the control draws a semi-transparent blue rectangle on the Skia canvas over the chart. The rectangle tracks the current selection. It is driven by the BrushSelectState that the controller exposes.

Hover tooltip

Hovering shows a tooltip with the nearest data point's series name and coordinates. NearestPointFinder searches all visible series within a configurable pixel distance (default 20px). A segment of a StateTimelineSeries is hit by containing the cursor, edges included, and the last one drawn answers where segments overlap; its tooltip names the event and the stretch it covers (Replay: Event 2 (30–45)).

The point the reader clicked

Clicking a data point pins an annotation to it, and it also tells your application which point it was. Subscribe to DataPointClicked on the control to open a detail panel, select a row in a grid beside the chart, or navigate:

using MatPlotLibNet;
using MatPlotLibNet.Avalonia;

string[] myRows = ["January", "February", "March"];

var chartControl = new MplChartControl
{
    Figure = Plt.Create().Plot([1.0, 2.0, 3.0], [2.0, 4.0, 3.0]).Build(),
    IsInteractive = true,
};

chartControl.DataPointClicked += point =>
{
    // point.SeriesLabel, point.DataX, point.DataY, point.PixelX, point.PixelY, point.AxesIndex,
    // and point.PointIndex / point.SeriesIndex: where the point sits in the arrays you passed in.
    Console.WriteLine($"Detail for {myRows[point.PointIndex]}");
};

The WPF, Avalonia, Uno and MAUI controls all carry the event under that name, their streaming controls too, and InteractionController raises it whether the chart applies its events in the control or publishes them to a server. A chart whose figure lives on the server reports the same click over SignalR: opt in with WithServerInteraction(id, i => i.EnableDataCursor()) and receive it with ChartSessionOptions.OnDataCursor. It needs IsInteractive, and a click counts when it lands within ten pixels of an actual point — a click that misses is a pan, as before. On a state timeline PointIndex is the segment's position in the list you passed, and a click anywhere inside a segment counts.

Platform details

WPF (MplChartControl, MplStreamingChartControl)

  • Both derive from MplChartSurface, an SKElement that draws through SkiaSharp and holds what the two share (the gestures, the handler, the clicked point, the paint); Figure, StreamingFigure and IsInteractive are dependency properties.
  • The control forwards its pointer, wheel and key events to the host, shows the rubber band of a brush and the tooltip of the nearest point, and takes WithServerInteraction to send gestures to a server.
  • Targets net8.0-windows10.0.19041.0 and later.

MAUI (MplChartView, MplStreamingChartView)

  • MplChartView inherits GraphicsView and draws through Microsoft.Maui.Graphics: hatches, gradients, the arcs of a pie and a donut and the library's own text metrics are drawn as the SVG and the PNG draw them.
  • Gestures come from MAUI's pan, pinch and tap recognizers and the graphics view's touch events, and reach the host through TouchGestureTranslator. DragAction is a bindable property.
  • MplStreamingChartView follows a streaming figure and draws it, and takes the gestures of MplChartView.

Avalonia (MplChartControl, MplStreamingChartControl)

  • Both derive from MplChartSurface, which inherits Control. It renders through ICustomDrawOperation, drawing on ISkiaSharpApiLeaseFeature.Lease().SkCanvas.
  • AffectsRender<MplChartControl>(FigureProperty) invalidates the control automatically when Figure changes.
  • The layout update is marshalled to the UI thread with Dispatcher.UIThread.Post(…).
  • Targets .NET 10 and .NET 8. Requires Avalonia 12.* with the Skia backend.

Uno (MplChartElement, MplStreamingChartElement)

  • Both derive from MplChartSurface, which inherits SKCanvasElement. RenderOverride(SKCanvas, Size) hands over the canvas directly.
  • Figure and IsInteractive are each a DependencyProperty.
  • The layout update is marshalled with DispatcherQueue.TryEnqueue().
  • Targets Windows 10 19041+, Android 21+, iOS 15+ and macCatalyst 15+.

See also

MatPlotLibNet 1.30.0

On the docs site

Clone this wiki locally