Repository navigation
Streaming
v1.4.0 — append data points to a live figure without rebuilding it. Typical uses are dashboards, telemetry and oscilloscopes.
using MatPlotLibNet;
using MatPlotLibNet.Models.Series.Streaming;
// 1. Build a streaming figure
StreamingLineSeries? series = null;
var sf = Plt.Create()
.WithTitle("Live Telemetry")
.AddSubPlot(1, 1, 1, ax => { series = ax.StreamingPlot(capacity: 5000); })
.BuildStreaming(TimeSpan.FromMilliseconds(33)); // 30fps throttle
// 2. Subscribe to render events (Avalonia example)
// sf.RenderRequested += () => Dispatcher.UIThread.Post(InvalidateVisual);
// 3. Append data from any thread
for (int i = 0; i < 1000; i++)
{
series!.AppendPoint(i, Math.Sin(i * 0.1));
await Task.Delay(10);
}
sf.Dispose();Data source (any thread) Render timer UI thread
│ │ │
AppendPoint(x, y) │ │
[write lock: ns] │ │
_version++ │ │
│ check DataVersion │
│ vs lastRendered │
│ │ │
│ fire RenderRequested ─────►│
│ │ marshal │
│ │ ▼
│ │ ApplyAxisScaling()
│ │ CreateSnapshot()
│ │ ChartRenderer.Render()
| Type | Description |
|---|---|
RingBuffer<T> |
A fixed-capacity circular sequence of any element type: a value, a record, a point in time. One writer, many readers (ReaderWriterLockSlim). An append never allocates; when the buffer is full, the append itself overwrites the oldest element. Measured at 64 M appends/s for double and 59 M/s for a four-field struct. |
RingBuffer<T>.Aggregate(seed, fold) |
Folds every held element into a caller-supplied state in one pass, without creating an intermediate collection. Computing the range of a 10 000-point series costs 33 bytes this way and 320 kB as a copy. |
RingBufferExtensions |
Min() and Max() for any INumber<T>, computed under one read lock without allocating. MinOrNaN() and MaxOrNaN() do the same for the double ring buffer that an axis reads. |
StreamingSnapshot |
Immutable point-in-time copy (double[] X, double[] Y, long Version). |
IStreamingSeries |
Contract: AppendPoint, AppendPoints, Clear, Version, Count, Capacity, CreateSnapshot. |
StreamingSeries |
Abstract base class with one RingBuffer<StreamingPoint>, a version counter and ComputeDataRange. It stores whole points in a single buffer instead of separate x and y buffers, so a snapshot is a single read and an x value can never be paired with a y value from a different sample. |
StreamingFigure |
Wraps a Figure. Owns the render timer and the version tracking, and provides ApplyAxisScaling() and the RenderRequested event. |
AxisScaleMode |
A sealed record hierarchy with the modes Fixed, AutoScale, SlidingWindow(size) and StickyRight(size). |
A line chart backed by a ring buffer. The default capacity is 10,000.
using MatPlotLibNet;
using MatPlotLibNet.Models.Series.Streaming;
using MatPlotLibNet.Styling;
StreamingLineSeries? series = null;
using var sf = Plt.Create()
.AddSubPlot(1, 1, 1, ax => series = ax.StreamingPlot(capacity: 10_000, configure: s =>
{
s.Color = Colors.Blue;
s.LineWidth = 2.0;
s.Label = "Sensor A";
}))
.BuildStreaming();
double timestamp = DateTime.Now.ToOADate();
double value = 21.5;
series!.AppendPoint(timestamp, value);A scatter plot backed by a ring buffer. The default capacity is 10,000.
using MatPlotLibNet;
using MatPlotLibNet.Models.Series.Streaming;
using MatPlotLibNet.Styling;
StreamingScatterSeries? series = null;
using var sf = Plt.Create()
.AddSubPlot(1, 1, 1, ax => series = ax.StreamingScatter(configure: s =>
{
s.Color = Colors.Orange;
s.MarkerSize = 4;
}))
.BuildStreaming();
series!.AppendPoint(1.0, 0.5);Stores Y values only. X is computed from SampleRate plus an offset. Optimized for oscilloscope, audio and telemetry data. The default capacity is 100,000.
using MatPlotLibNet;
using MatPlotLibNet.Models.Series.Streaming;
using MatPlotLibNet.Styling;
StreamingSignalSeries? signal = null;
using var sf = Plt.Create()
.AddSubPlot(1, 1, 1, ax => signal = ax.StreamingSignal(capacity: 100_000, sampleRate: 44100.0, configure: s =>
{
s.Color = Colors.Green;
}))
.BuildStreaming();
double amplitude = 0.25;
double[] buffer = Enumerable.Range(0, 441).Select(i => Math.Sin(2 * Math.PI * 440 * i / 44100.0)).ToArray();
signal!.AppendSample(amplitude);
signal.AppendSamples(buffer); // batch appendFour parallel ring buffers, one each for open, high, low and close (O/H/L/C). Raises the BarAppended event, which streaming indicators use to attach themselves. The default capacity is 5,000.
using MatPlotLibNet;
using MatPlotLibNet.Data;
using MatPlotLibNet.Models.Series.Streaming;
StreamingCandlestickSeries? candles = null;
using var sf = Plt.Create()
.AddSubPlot(1, 1, 1, ax => candles = ax.StreamingCandlestick(capacity: 5000))
.BuildStreaming();
candles!.AppendBar(open: 100, high: 110, low: 95, close: 105);
candles.AppendBar(new OhlcBar(105, 115, 100, 110));Control how axes auto-scale when streaming data arrives.
using MatPlotLibNet;
using MatPlotLibNet.Models.Streaming;
using var sf = Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax.StreamingPlot())
.BuildStreaming();
sf.DefaultConfig = new StreamingAxesConfig(
new AxisScaleMode.SlidingWindow(100.0), // X: show last 100 units
new AxisScaleMode.AutoScale()); // Y: fit all visible data| Mode | Behavior |
|---|---|
Fixed |
User-set limits, never auto-adjusted |
AutoScale |
Fit all data every render |
SlidingWindow(size) |
Show last N X-units, scroll as data arrives |
StickyRight(size) |
Like SlidingWindow but only scroll when at the right edge |
57 of the 59 technical indicators have a streaming form: after the bar at index i its value is the last value of the batch indicator over the bars up to i, to 1e-9, and a test holds every form to that over every prefix of 200 bars. A form attaches to a StreamingCandlestickSeries through its OhlcvBarAppended event, which carries the bar's volume (AppendBar(OhlcvBar); a bar without one has NaN for a volume). Each form writes its output to its own StreamingLineSeries, so the renderer needs no changes. WithStreaming(axes, indicator) attaches any of them, and the eleven named verbs below are that call with the indicator made for you. The root of a form is StreamingIndicator<TInput>, whatever it reads: a bar (OhlcvBar), a price, a row of several series, or a TransferEntropySample. The 11 forms that came first are StreamingIndicator<double> (a price), StreamingIndicator<OhlcvBar> (a bar) and StreamingIndicator<TradedPrice> (a price with its volume).
using MatPlotLibNet;
using MatPlotLibNet.Indicators.Streaming;
using MatPlotLibNet.Models.Series.Streaming;
StreamingCandlestickSeries? candles = null;
using var sf = Plt.Create()
.AddSubPlot(1, 1, 1, ax => candles = ax.StreamingCandlestick(5000))
.BuildStreaming();
// An indicator draws its lines on the axes the candles live on.
var axes = sf.Figure.SubPlots[0];
var bars = candles!;
bars.WithStreamingSma(axes, 20); // auto-appends SMA line
bars.WithStreamingBollinger(axes, 20, 2.0); // auto-appends 3 band lines
bars.WithStreamingRsi(axes, 14); // auto-appends RSI line| Indicator | Output | Complexity |
|---|---|---|
StreamingSma |
Rolling average | O(1) |
StreamingEma |
Exponential average | O(1) |
StreamingRsi |
Wilder's RSI (0–100) | O(1) |
StreamingBollinger |
3 series: mid, upper, lower | O(1) |
StreamingMacd |
3 series: MACD, signal, histogram | O(1) |
StreamingObv |
Cumulative volume | O(1) |
StreamingAtr |
Wilder's true range | O(1) |
StreamingStochastic |
2 series: %K, %D | O(1) amortized |
StreamingWilliamsR |
Rolling min/max | O(1) amortized |
StreamingCci |
Mean deviation | O(n/period) |
StreamingVwap |
Cumulative price*vol / vol; AnchorHere() restarts it at the next bar |
O(1) |
The other 46 forms are named Streaming and the indicator (StreamingAdx, StreamingSupertrend, StreamingMamaFama, StreamingTransferEntropy, and so on). They keep their cost in one of five ways:
| Shape | What a form keeps | Indicators |
|---|---|---|
| Window | The last bars, and the batch indicator is run over them | Amihud illiquidity, Aroon oscillator, CG oscillator, Corwin–Schultz, ease of movement, fractional differentiation, Garman–Klass, Ichimoku, inverse Fisher transform, Kaufman efficiency ratio, permutation entropy, profit/loss, relative vigor index, ROC, Roll spread, squeeze momentum, transfer entropy, volume indicator, VPIN, VWAP z-score, wavelet energy ratio, wavelet entropy, Yang–Zhang and its volatility ratio |
| Recursive | The state of the recursion, a step the batch indicator folds over too | Adaptive stochastic, ADX, BOCPD, CyberCycle, decycler, Ehlers' instantaneous trend, sine wave and SuperSmoother, force index, Keltner channels, Laguerre RSI, MAMA/FAMA, roofing filter, Twiggs money flow |
| State machine | A state that changes by rule | CUSUM, Klinger volume oscillator, Parabolic SAR, Supertrend |
| Cumulative | A running total | Drawdown, equity curve |
| Multivariate | One row of several series at a time | Dispersion index, turbulence index |
FibonacciRetracement and VolumeProfile have no streaming form: the first is five fixed levels drawn from two numbers you give, and the second a histogram of the whole range whose edges move with every new extreme, so neither has a value per bar for a stream to say. The classification is written once, in StreamingMap, and a calculator added without a line there turns a test red.
using MatPlotLibNet;
using MatPlotLibNet.Indicators.Streaming;
using MatPlotLibNet.Models.Series.Streaming;
StreamingCandlestickSeries? candles = null;
using var sf = Plt.Create()
.AddSubPlot(1, 2, 1, ax => candles = ax.StreamingCandlestick(5000))
.AddSubPlot(1, 2, 2, ax => ax.Plot([0.0], [0.0]))
.BuildStreaming();
// Any indicator, attached by WithStreaming; its lines land on the axes you name.
var adx = candles!.WithStreaming(sf.Figure.SubPlots[1], new StreamingAdx(14, 5000));
Console.WriteLine(adx.WarmupPeriod);An indicator that reads two series, such as transfer entropy, is fed TransferEntropySamples, and with a window it says one value for each sample once the window is full.
All 6 UI hosts use StreamingFigure in the same way: subscribe to RenderRequested, marshal the call to the UI thread, and invalidate the view.
| Host | Control | Marshal |
|---|---|---|
| WPF | MplStreamingChartControl |
Dispatcher.BeginInvoke |
| Avalonia | MplStreamingChartControl |
Dispatcher.UIThread.Post |
| Uno | MplStreamingChartElement |
DispatcherQueue.TryEnqueue |
| MAUI | MplStreamingChartView |
MainThread.BeginInvokeOnMainThread |
| Blazor | MplStreamingChart |
InvokeAsync + StateHasChanged
|
| ASP.NET Core | StreamingChartSession |
IChartPublisher.PublishSvgAsync |
<wpf:MplStreamingChartControl StreamingFigure="{Binding LiveChart}" />Bind the figure once and leave it there. The ordinary MplChartControl takes a Figure and redraws when that
property changes — which, for a dependency property, means when the reference changes — so driving a streaming
figure through it meant handing it null and the same figure again to fake a change.
<avalonia:MplStreamingChartControl StreamingFigure="{Binding LiveChart}" /><MplStreamingChart StreamingFigure="@_streamingFigure" />using MatPlotLibNet;
using MatPlotLibNet.AspNetCore;
using MatPlotLibNet.Models.Series.Streaming;
using MatPlotLibNet.Models.Streaming;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMatPlotLibNetSignalR();
var app = builder.Build();
app.MapChartHub();
StreamingLineSeries? series = null;
var figure = Plt.Create()
.AddSubPlot(1, 1, 1, ax => series = ax.StreamingPlot())
.Build();
// In a background service:
var sf = new StreamingFigure(figure);
app.Services.GetRequiredService<FigureRegistry>().RegisterStreaming("dashboard-1", sf);
// sf.RenderRequested auto-publishes SVG to all connected clients
series!.AppendPoint(0, 21.5);
app.Run();Connect IObservable<T> sources to a streaming series. No dependency on System.Reactive is needed:
using MatPlotLibNet;
using MatPlotLibNet.Data;
using MatPlotLibNet.Models.Series.Streaming;
StreamingLineSeries? series = null;
StreamingCandlestickSeries? candles = null;
using var sf = Plt.Create()
.AddSubPlot(2, 1, 1, ax => series = ax.StreamingPlot())
.AddSubPlot(2, 1, 2, ax => candles = ax.StreamingCandlestick())
.BuildStreaming();
// Any IObservable<T> will do: an Rx Subject<T>, a SignalR stream, a device driver. Feed<T> below is the smallest one.
var sensorStream = new Feed<StreamingPoint>(); // StreamingPoint(double X, double Y)
using var subscription = series!.SubscribeTo(sensorStream);
var priceStream = new Feed<OhlcBar>();
using var ohlcSub = candles!.SubscribeTo(priceStream);
sensorStream.Push(new StreamingPoint(0, 21.5));
priceStream.Push(new OhlcBar(100, 110, 95, 105));
sealed class Feed<T> : IObservable<T>
{
private readonly List<IObserver<T>> _observers = [];
public void Push(T value)
{
foreach (var observer in _observers.ToArray())
observer.OnNext(value);
}
public IDisposable Subscribe(IObserver<T> observer)
{
_observers.Add(observer);
return new Subscription(() => _observers.Remove(observer));
}
private sealed class Subscription(Action leave) : IDisposable
{
public void Dispose() => leave();
}
}For Blazor and other web scenarios, SvgDiffEngine computes a minimal patch between two renders. The patch is typically 10x smaller than the full SVG:
using MatPlotLibNet;
using MatPlotLibNet.Rendering.Svg;
double[] x = [0, 1, 2, 3];
string previousSvg = Plt.Create().Plot(x, [0, 1, 4, 9]).ToSvg();
string currentSvg = Plt.Create().Plot(x, [0, 1, 4, 10]).ToSvg();
var patch = SvgDiffEngine.Compute(previousSvg, currentSvg);
if (patch.IsFullReplace)
{
Console.WriteLine($"send the full SVG: {currentSvg.Length} characters");
}
else
{
foreach (var entry in patch.Patches) // only changed series groups
Console.WriteLine($"send series {entry.SeriesIndex}: {entry.NewContent.Length} characters");
}| Scenario | Buffer | Throttle | Memory |
|---|---|---|---|
| Dashboard (1/sec) | 1,000 | 1000ms | 16 KB |
| Telemetry (100/sec) | 10,000 | 33ms | 640 KB |
| Oscilloscope (10K/sec) | 100,000 | 16ms | 800 KB |
| Trading (OHLC, 10/sec) | 5,000 | 100ms | 160 KB |
Tips:
- Set
MinRenderIntervalto match your target FPS - Use
StreamingSignalSeries(Y-only) for uniform sample rates; it saves 50% memory compared with an XY series - The ring buffer never allocates on append;
CreateSnapshot()allocates once per render - For more than 100K points, consider LTTB downsampling on the snapshot; the existing
MaxDisplayPointssetting is respected
MatPlotLibNet 1.30.0
- Home
- Getting Started
- Fluent Cheatsheet
- Examples — each release in code
- Migrating to 1.30.0 — what was removed and what takes its place
-
Package Map
- MatPlotLibNet — the core package
- Chart Types
- Styling
- Advanced
- Streaming
- Bidirectional SignalR
- Interactive Controls
- MCP Server
- Verso
- Notebooks
- Accessibility
- International Text
- Benchmarks
- Roadmap
- Contributing
On the docs site
- Playground — try a chart in the browser
- Cookbook — copy-paste code with its picture
- API reference — every public type and member