Repository navigation
Fluent Cheatsheet
Coming from Python? From matplotlib to C# puts every pyplot call beside the line that draws the same chart here.
This page is a one-page reference for MatPlotLibNet's fluent builder API. Every chart starts at Plt.Create() and ends at an output call (ToSvg, Save, …). In between, you chain figure-level methods on FigureBuilder and per-subplot methods on AxesBuilder via AddSubPlot(..., ax => ax.Plot(...)).
| Call | Returns | Purpose |
|---|---|---|
Plt.Create() |
FigureBuilder |
The normal entry point. Starts fluent construction. |
Plt.Figure(width, height) |
Figure |
Creates the model directly, without the builder. Rarely used. |
Plt.Mosaic("AB;CC", ...) |
MosaicFigureBuilder |
Defines the subplot layout from an ASCII-art string. |
Plt.Style.Use(...) |
void | Applies a global stylesheet (e.g. "seaborn"). |
Plt.Style.Context(...) |
StyleContext |
Applies a style override for the scope of a using block. |
using MatPlotLibNet;
using MatPlotLibNet.Styling;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
Plt.Create()
.WithSize(900, 600) // px — intrinsic / viewBox size
.WithDpi(150) // a PNG is drawn at 150 dpi: 900 × 600 becomes 1406 × 938 pixels
.WithTitle("Q1 Report")
.WithTheme(Theme.MatplotlibV2) // or MatplotlibClassic, HighContrast, ColorBlindSafe
.WithBackground(Colors.White)
.WithAltText("Accessible description")
.WithResponsiveSvg(false) // opt out of the responsive default (max-width:100%;height:auto)
.Plot(x, y)
.Save("report.svg");using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
// classic: rows, cols, 1-based index
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax.Plot(x, y))
.Save("single.svg");
// GridSpec-based: uneven row heights, and a panel that spans both columns
Plt.Create()
.WithGridSpec(3, 2, heightRatios: [2, 1, 1])
.AddSubPlot(new GridPosition(0, 1, 0, 2), ax => ax.Plot(x, y)) // row 0, columns 0 and 1
.AddSubPlot(GridPosition.Single(1, 0), ax => ax.Bar(["A", "B"], [3, 5]))
.AddSubPlot(GridPosition.Single(1, 1), ax => ax.Scatter(x, y))
.AddSubPlot(new GridPosition(2, 3, 0, 2), ax => ax.Step(x, y))
.Save("gridspec.svg");using MatPlotLibNet;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
FigureBuilder TwoPanels() => Plt.Create()
.AddSubPlot(1, 2, 1, ax => ax.Plot(x, y).SetYLabel("Left"))
.AddSubPlot(1, 2, 2, ax => ax.Plot(x, y).SetYLabel("Right"));
TwoPanels().TightLayout().Save("tight.svg"); // auto-compute margins from measured text
TwoPanels().ConstrainedLayout().Save("constrained.svg"); // same idea, more aggressive
TwoPanels().WithSubPlotSpacing(s => s with { MarginTop = 60 }) // manual override
.Save("manual.svg");using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
var shade = new double[8, 64];
for (int row = 0; row < 8; row++)
for (int column = 0; column < 64; column++)
shade[row, column] = column;
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax.WithLegend(visible: false).Plot(x, y, s => s.Label = "Signal"))
.FigText("Source: field survey", 0.01, 0.01) // fractions of the figure from its bottom-left corner
.FigLegend(legend => legend with { Position = LegendPosition.LowerRight }) // lists the labelled series of every subplot; each call adds a legend
.FigImage(shade, 20, 20, image => image.Alpha = 0.6) // each value one pixel, offsets in pixels, under the subplots
.Save("figure-overlays.svg");The three are drawn in the SVG and in every raster and native output, on a figure with no subplot at all. The figure's legend is
static; at an outside place ConstrainedLayout() keeps room for it, at any other it takes none. See the examples page.
using MatPlotLibNet;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
Plt.Create()
.WithZoomPan() // drag-to-pan, wheel-to-zoom
.WithLegendToggle() // click a legend entry → hide/show series
.WithRichTooltips() // hover a point → tooltip
.WithHighlight() // hover a series → dim others
.WithSelection() // click to select points
.With3DRotation() // drag a 3D plot to rotate
.WithTreemapDrilldown() // every depth visible by default; click a parent rect to collapse its entire subtree, click again to restore
.WithSankeyHover() // hover a Sankey node → isolate reachable flow chain
.LinkSelection("orders") // a brush on one chart lights the same rows on every chart of the group (a series names its rows with RowKeys)
.Plot(x, y, s => s.Label = "Signal")
.Save("interactive.svg");using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
var chart = Plt.Create().Plot(x, y);
string svg = chart.ToSvg(); // string
chart.Save("chart.svg"); // .svg / .json, and .png / .pdf once MatPlotLibNet.Skia is registered
string json = chart.ToJson(indented: true); // serialize the figure
Figure figure = chart.Build(); // Figure model (skip rendering)using MatPlotLibNet;
using MatPlotLibNet.Interactive;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
var figure = Plt.Create().Plot(x, y).Build();
var handle = await figure.ShowAsync(); // opens a self-hosted browser popup
figure.Title = "Updated"; // change the figure the handle shows…
await handle.UpdateAsync(); // …and push the new version to the browserThere is no synchronous Show(); it was removed in v1.13.0. The handle does not own the embedded server: that server lives as long as the process.
These shortcuts are useful for single-plot figures:
using MatPlotLibNet;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
string[] cats = ["A", "B", "C"];
double[] vals = [10, 20, 15];
Plt.Create().Plot(x, y).Save("line.svg");
Plt.Create().Bar(cats, vals).Save("bar.svg");
Plt.Create().Scatter(x, y).Save("scatter.svg");The families supported at figure level are Plot / Scatter / Bar / Hist / Pie / Image / Histogram2D / Treemap / Sunburst / Sankey / Surface / Scatter3D / Bar3D / PolarPlot / ErrorBar / Step / FillBetween / Kde and many more. Heatmap, BoxPlot, Violin, Candlestick and OhlcBar are on AxesBuilder only.
using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] x = [1, 2, 3, 4, 5];
double[] y = [20, 40, 30, 50, 10];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.WithTitle("Revenue")
.SetXLabel("Quarter")
.SetYLabel("USD")
.SetZLabel("Units") // 3D only
.SetXLim(1, 10)
.SetYLim(0, 100)
.SetXScale(AxisScale.Log)) // Linear, Log, SymLog, Logit
.Save("labels.svg");using MatPlotLibNet;
using MatPlotLibNet.Rendering.TickFormatters;
using MatPlotLibNet.Rendering.TickLocators;
double[] x = [1, 2, 3, 4, 5];
double[] share = [0.12, 0.25, 0.31, 0.48, 0.55];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, share)
.SetXTickLocator(new MaxNLocator(5))
.SetYTickLocator(new AutoLocator())
.SetYTickFormatter(new PercentFormatter(1.0)) // 0.25 → 25%
.WithMinorTicks()
.WithYTicksMirrored() // ticks on both left AND right (v1.4.1)
.WithXTicksMirrored() // ticks on both top AND bottom (v1.4.1)
.WithYTickLabelsOnRight() // Y labels on the right only, marks on both edges
.WithTightMargins() // SetXMargin(0).SetYMargin(0) — data touches spines, no nice-bounds expansion
.WithXTickLabelRotation(30) // rotate X-tick labels; auto-30° when labels would overlap
.WithYTickLabelRotation(45)) // rotate Y-tick labels
.Save("ticks.svg");
DateTime[] days = [new(2026, 1, 1), new(2026, 2, 1), new(2026, 3, 1)];
double[] sales = [12, 15, 11];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(days, sales)
.SetXDateAxis() // interprets X as DateTime
.SetXDateFormat("yyyy-MM"))
.Save("dates.svg");using MatPlotLibNet;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.HideTopSpine()
.HideRightSpine()
.WithSpines(s => s with { Left = s.Left with { LineWidth = 2 } }))
.Save("spines.svg");
// a range frame: each line spans only the data, in the data units of its own axis
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.WithSpines(s => s with { Bottom = s.Bottom with { BoundsFrom = 1, BoundsTo = 5 } }))
.Save("range_frame.svg");
// an equal scale: a unit of Y is as long on the page as a unit of X (a square of data is a square)
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax.Plot(x, y).SetAspect(1))
.Save("equal.svg");
// an axis turned round, as matplotlib's invert_yaxis(): high values at the bottom; a toggle, so a second call turns it back
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax.Plot(x, y).InvertYAxis())
.Save("inverted.svg");
// the X tick labels along the top only, the marks on both edges, as matplotlib's matshow numbers its columns
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax.Plot(x, y).WithXTickLabelsOnTop())
.Save("labels_on_top.svg");
// an image keeps square cells under the matplotlib themes (image.aspect 'equal'); SetAspectAuto() stretches it over the plot
double[,] cells = { { 1, 2, 3 }, { 4, 5, 6 } };
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax.Image(cells).SetAspectAuto())
.Save("image_auto.svg");
// a bare canvas: no spines, no ticks, no labels (a Sankey or a Treemap draws without axes on its own)
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax.HideAllAxes().Plot(x, y))
.Save("bare.svg");using MatPlotLibNet;
using MatPlotLibNet.Models;
using MatPlotLibNet.Styling;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y, s => s.Label = "Signal")
.WithLegend(LegendPosition.UpperRight)
.WithLegend(l => l with { Position = LegendPosition.OutsideRight, NCols = 2, Title = "Series" })
.WithLegendValues() // appends each XY series' last Y value to its legend entry
.ShowGrid()
.WithGrid(g => g with { Color = Colors.LightGray, LineStyle = LineStyle.Dashed }))
.TightLayout()
.Save("legend.svg");Legend positions: there are 11 inside positions (UpperRight, UpperLeft, LowerRight, LowerLeft, Right, CenterLeft, CenterRight, LowerCenter, UpperCenter, Center, Best) and 4 outside positions (OutsideRight, OutsideLeft, OutsideTop, OutsideBottom). Constrained layout reserves space for the outside positions. Best, the default, looks at the marks the chart drew and takes the place that covers the fewest, as matplotlib's loc='best' does; the classic theme puts a legend that names no position in the upper right.
Order-independent WithLegend (v1.13.0 fix): WithLegend(position, visible) updates only Visible and Position. Every other property is preserved, whatever the call order. .WithLegendValues().WithLegend(LegendPosition.UpperRight) and the reverse order give the same result.
LegendValues last-value suffix: WithLegendValues(enabled: true) appends each labelled XYSeries' last data value to its legend entry. For example, Signal becomes Signal = 2.70; the value is formatted with invariant culture F2. Non-XY series show the label text only. The default is false.
using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] x = [0, 1, 2, 3, 4, 5, 6];
double[] y = [0, 1, 4, 9, 16, 25, 36];
double[] zoomX = [2, 2.5, 3, 3.5, 4];
double[] zoomY = [4, 6.25, 9, 12.25, 16];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.AddInset(new InsetBounds(0.55, 0.55, 0.4, 0.4), inset => inset
.Plot(zoomX, zoomY)
.SetXLim(2, 4)))
.Save("inset.svg");
// convenience overload — forwards to the InsetBounds overload above (canonical form, v1.13.0)
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.AddInset(x: 0.55, y: 0.55, width: 0.4, height: 0.4, inset => inset.Plot(zoomX, zoomY)))
.Save("inset-short.svg");InsetBounds(X, Y, Width, Height) is a readonly record struct. Its values are fractions (0-1) of the parent axes: Y is the
inset's top edge counted down from the top of the parent, where matplotlib's inset_axes counts up from the bottom.
IndicateZoom() on the inset's builder has the parent draw a rectangle over the region the inset shows, and the two lines from it
to the inset's frame that matplotlib's rule keeps:
using MatPlotLibNet;
using MatPlotLibNet.Styling;
double[] x = [.. Enumerable.Range(0, 200).Select(i => i / 20.0)];
double[] y = [.. x.Select(v => Math.Sin(v) + 0.3 * Math.Sin(5 * v))];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.SetYLim(-1.5, 3.5)
.AddInset(0.5, 0.03, 0.45, 0.35, inset => inset
.Plot(x, y)
.SetXLim(6, 7.5)
.SetYLim(-0.7, 1)
.IndicateZoom(zoom => zoom.Color = Colors.Red))) // left out: the theme's grey at half opacity, with connectors
.Save("inset-zoom.svg");using MatPlotLibNet;
double[] t = [1, 2, 3, 4, 5];
double[] price = [101, 103, 102, 106, 108];
double[] volume = [1200, 900, 1500, 1100, 1300];
Plt.Create()
.AddSubPlot(2, 1, 1, ax => ax
.Plot(t, price)
.WithAddRightYAxis(y2 => y2.Plot(t, volume).SetYLabel("Volume")), key: "time-axis")
.AddSubPlot(2, 1, 2, ax => ax.ShareX("time-axis").Step(t, volume)) // follows the X range of the keyed panel
.Save("shared.svg");Every Y axis of a subplot belongs to one container, and the primary Y axis is the first axis of its left side. Call
WithAddRightYAxis or WithAddLeftYAxis once for each further axis; each call stacks one more axis outward past the
ones already on that side, with no cap:
using MatPlotLibNet;
double[] t = [1, 2, 3, 4, 5];
double[] price = [101, 103, 102, 106, 108];
double[] volume = [1200, 900, 1500, 1100, 1300];
double[] rate = [2.1, 2.3, 2.2, 2.6, 2.8];
double[] queue = [4, 9, 7, 12, 10];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(t, price).SetYLabel("Price") // the primary axis, first on the left
.WithAddRightYAxis(y2 => y2.Plot(t, volume).SetYLabel("Volume")) // right, nearest the plot
.WithAddRightYAxis(y3 => y3.Plot(t, rate).SetYLabel("Rate (%)")) // right, stacked past the one before
.WithAddLeftYAxis(y4 => y4.Plot(t, queue).SetYLabel("Queue")) // left, next to the primary axis
.WithYAxisTitleGap(6)) // px between a title and its tick labels
.Save("many-axes.svg");| Call | Returns | Purpose |
|---|---|---|
WithAddRightYAxis(Action<YAxisSlotBuilder>) |
AxesBuilder |
Stacks one more Y axis on the right, past every right axis already there. A null callback throws ArgumentNullException. |
WithAddLeftYAxis(Action<YAxisSlotBuilder>) |
AxesBuilder |
The same on the left, past the primary Y axis and every left axis already added. |
WithYAxisTitleGap(double pixels) |
AxesBuilder |
The blank gap between every Y axis title and its tick labels, and between two stacked axes, on both sides. 4 by default (matplotlib's axes.labelpad under the matplotlib themes: 4 pt under v2, 5 pt under classic); a negative, NaN or infinite value throws. |
The callback's YAxisSlotBuilder has the same verbs for every axis: SetYLabel, SetYLim, SetYAxisColor, Plot,
Scatter, StreamingPlot, WithDirectLabel and Link. A scale, a tick locator or minor ticks are settings of the axis
itself, reached through axes.YAxes.Right[0].Axis, axes.YAxes.Left[1].Axis and so on.
Link(transform) makes an axis show the primary axis' values in another unit, matplotlib's secondary_yaxis (on a Y axis
past the primary) and secondary_xaxis (on the top axis, through WithSecondaryXAxis). A linked axis has no range and no
series of its own; each tick stands where the primary has the value it maps back to:
using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] t = [1, 2, 3, 4, 5];
double[] celsius = [12, 15, 19, 17, 14];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(t, celsius).SetYLabel("°C")
.WithAddRightYAxis(f => f.SetYLabel("°F").Link(AxisTransform.Linear(1.8, 32))) // scale × value + offset
.WithSecondaryXAxis(top => top.SetXLabel("1 / t").Link(AxisTransform.Reciprocal()))) // numerator / value
.Save("linked.svg");AxisTransform |
Shows | Places a range |
|---|---|---|
Linear(scale, offset = 0) |
scale × value + offset |
everywhere |
Reciprocal(numerator = 1) |
numerator / value |
on one side of 0 |
Logarithm(base = 10) |
the logarithm of the value | above 0 |
Power(exponent) |
the value raised to the exponent | on 0 and above |
Of(forward, inverse) |
your own pair of functions; not written to JSON | where it runs one way |
WithAddBottomXAxis stacks a linked X axis below the plot, matplotlib's secondary_xaxis('bottom'): below the primary X
axis' tick labels and title, each further one below the one before, or at a fraction of the plot's height from the bottom
spine with SetLocation (matplotlib's secondary_xaxis(-0.2)). Its builder, XAxisSlotBuilder, has SetXLabel,
SetXAxisColor, Link and SetLocation; the axis holds no series:
using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] celsius = [0, 25, 50, 75, 100];
double[] rate = [1, 3, 4, 3, 2];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(celsius, rate).SetXLabel("°C")
.WithAddBottomXAxis(f => f.SetXLabel("°F").Link(AxisTransform.Linear(1.8, 32))) // below the °C title
.WithAddBottomXAxis(k => k.SetXLabel("K").Link(AxisTransform.Linear(1, 273.15)).SetLocation(-0.4)))
.Save("linked_below.svg");The verbs, builders and accessors that put a second, third or fourth Y axis on a subplot before the container are removed in
1.30.0. An axis is added with WithAddRightYAxis(...) or WithAddLeftYAxis(...), whose lambda takes a YAxisSlotBuilder, and
the axes of a side are Axes.YAxes.Right and Axes.YAxes.Left (slot 0 of the left side is the primary axis). Migrating to 1.30.0
names each removed call and its replacement.
using MatPlotLibNet;
using MatPlotLibNet.Styling;
double[] t = [1, 2, 3, 4, 5];
double[] price = [101, 103, 102, 106, 108];
double[] volume = [1200, 900, 1500, 1100, 1300];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(t, price, s => { s.Label = "Price"; s.Color = Colors.Navy; })
.WithDirectLabel() // the name at the end of the line, not in the legend
.SetYAxisColor(Colors.Navy) // spine, ticks, tick labels and title in one colour
.WithAddRightYAxis(y2 => y2
.Plot(t, volume, s => { s.Label = "Volume"; s.Color = Colors.Coral; })
.WithDirectLabel()
.SetYAxisColor(Colors.Coral))) // SetXAxisColor does the same for the bottom axis and WithSecondaryXAxis
.Save("direct-labels.svg");WithDirectLabel() acts on the line added just before it (LabelPlacement = SeriesLabelPlacement.LineEnd on the series
says the same). Pictures of both are on the examples page.
using MatPlotLibNet;
using MatPlotLibNet.Styling.ColorMaps;
double[,] density = { { 1, 10, 100 }, { 5, 50, 500 }, { 2, 20, 1000 } };
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Heatmap(density)
.WithColorMap("viridis") // or ColorMaps.Viridis
.WithColorBar(cb => cb with { Label = "Density" })
.WithNormalizer(new LogNormalizer()))
.Save("density.svg");using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] x = [1, 2, 3, 4, 5];
double[] y = [5, 12, 95, 15, 98];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.WithYBreak(20, 80, BreakStyle.Zigzag))
.Save("broken.svg");Every series method takes a final optional Action<T> configure to tweak properties.
| Family | Methods |
|---|---|
| XY line/scatter |
Plot(x, y), Scatter(x, y), DensityScatter(x, y) (markers coloured by how crowded they are), ErrorBar(x, y, yErrLow, yErrHi), Step(x, y), FillBetween(x, y, y2) (the GradientColor of a bar or an area series fades its fill), FillBetweenX(y, x1, x2?) (the area lying down), StackPlot(x, ySets) (name the layers with Labels and each is a legend entry) |
| Signal / realtime |
SignalXY(x, y) (monotonic X, fast), Signal(y, sampleRate, xStart) (sample rate and offset) |
| Categorical |
Bar(cats, vals), GroupedBar(cats, groups) (several bars per category in one call), BrokenBarH(ranges), Gantt(tasks, starts, ends) (the rows named by the tasks, the first on top, each task its own colour of the cycle), Waterfall(cats, vals) (Targets marks a level on each bar), Waffle(cats, vals) (square cells counted by share), Eventplot(positions), Countplot(values)
|
| Distribution |
Hist(data, bins), BoxPlot(datasets), Violin(datasets), Kde(data), Ecdf(data), Rugplot(data), Stripplot(datasets), Swarmplot(datasets)
|
| 2D grid |
Heatmap(data), Image(data), Pcolormesh(x, y, c), Histogram2D(x, y, bins), Contour(x, y, z), Contourf(x, y, z), Hexbin(x, y), Tricontour(x, y, z), Tripcolor(x, y, z)
|
| Circular |
Pie(sizes, labels), Donut(sizes, labels)
|
| Hierarchical |
Treemap(root), Sunburst(root), NestedPie(root), Icicle(root) — all take TreeNode root
|
| Flow |
Sankey(nodes, links) with SankeyNode[] and SankeyLink[], Chord(names, flows) (the flows between groups as a ring of arcs with a ribbon for each flow; flows is a square double[,]) |
| Text |
WordCloud(words, weights) (words sized by the square root of their weight and packed without overlap) |
| Ternary |
TernaryScatter(top, left, right), TernaryPlot(top, left, right) (a line), Piper(samples) (the samples are WaterSample values in mg/L); the corners are named by SetYLabel (apex), SetZLabel (bottom left) and SetXLabel (bottom right) |
| Polar |
PolarPlot(r, θ), PolarScatter(r, θ), PolarBar(r, θ) (with SetBarMode(BarMode.Stacked) the bars of the axes stack), PolarHeatmap(data, θBins, rBins), Radar(cats, vals)
|
Map (MatPlotLibNet.Geo) |
WithProjection(p), then Land(color), Ocean(color), Borders(), Coastlines(), Choropleth(values, colorMap), Points(lat, lon), Bubbles(lat, lon, values), HexBins(lat, lon), Flows(flows), Cartogram(values), ContiguousCartogram(values), Dorling(values) — all read the axes' one projection |
| Financial |
Candlestick(open, high, low, close, dateLabels?), OhlcBar(open, high, low, close, dateLabels?), PointAndFigure(prices, boxSize, reversal?)
|
| Pair-selection |
RelativeRotation(assetCloses, benchmarkCloses, labels) — an RRG chart: a 2D scatter of RS-Ratio against RS-Momentum, with a fading tail |
| 3D |
Surface(x, y, z), Wireframe(x, y, z), Scatter3D(x, y, z), Stem3D(x, y, z), Bar3D(x, y, z), PlanarBar3D(x, y, z)
|
| Field |
Quiver(x, y, u, v), Streamplot(x, y, u, v), Barbs(x, y, speed, dir), QuiverKey(x, y, u, label)
|
| Special |
Gauge(value), ProgressBar(value), Sparkline(values), Bubble(x, y, sizes), Funnel(labels, values), Regression(x, y), Residplot(x, y), Pointplot(datasets), Spectrogram(signal), Table(cellData)
|
These verbs build a whole chart from the series above, thirty-eight of them. They live in six classes in the namespace MatPlotLibNet, and
the class is the shape of the data: names, a sample, x positions, the cells of a grid, a series of prices or a signal. Optional inputs come before
the last argument, configure.
| Data | Verbs |
|---|---|
Names (CategoricalAxesExtensions) |
Lollipop(categories, values), Dumbbell(categories, from, to), Pareto(categories, counts), SlopeGraph(categories, from, to), DotPlot(categories, groups), ParallelCoordinates(dimensions, rows), Marimekko(columns, segments)
|
A sample (DistributionAxesExtensions) |
Ridgeline(groups, bandwidth?), QQPlot(sample), ProbabilityPlot(sample, reference), KaplanMeier(groups), RiskTable(groups, times?), Raincloud(groups), StemAndLeaf(sample, leafUnit?)
|
x positions (XYAxesExtensions) |
BumpChart(x, ranks), ControlChart(x, values, limits?), ShewhartChart(data, rules, limits?), StreamGraph(x, layers, baseline?), Horizon(x, values), ConnectedScatter(x, y), VLines(x, yMin, yMax), HLines(y, xMin, xMax), Stairs(values, edges, baseline?) (StairsParts: an outline, or a fill with a baseline), Triplot(x, y, triangles?)
|
Cells (GridAxesExtensions) |
CalendarHeatmap(dates, values, firstDayOfWeek?), Spy(matrix, threshold?), MatShow(matrix), CalendarEvents(dates, kinds)
|
Prices (PriceAxesExtensions) |
Renko(prices, brickSize), Kagi(prices, reversal)
|
A signal (SignalAxesExtensions) |
Psd(signal, options?), Csd(x, y, options?), Cohere(x, y, options?) (a SpectralOptions: Welch's method, matplotlib's defaults), MagnitudeSpectrum(signal, options?, scale?), PhaseSpectrum(signal, options?), AngleSpectrum(signal, options?) (a SpectrumOptions), Acorr(signal, options?), Xcorr(x, y, options?) (a CorrelationOptions, drawn as stems or as markers; CorrelationParts) |
A group of named values is a BarGroup(label, values), a sample a NamedSample(label, values), a survival arm a
SurvivalGroup(label, durations, observed). Each verb is shown with its picture on the examples page and the pages of the releases after it (the newest is 1.28.0).
The configure callback runs against the concrete series instance. The examples below show representative property sets:
using MatPlotLibNet;
using MatPlotLibNet.Models;
using MatPlotLibNet.Models.Series;
using MatPlotLibNet.Styling;
using MatPlotLibNet.Styling.ColorMaps;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
double[] bubbleSizes = [20, 60, 40, 80, 30];
double[] density = [0.1, 0.5, 0.3, 0.9, 0.2];
string[] cats = ["A", "B", "C", "D"];
double[] vals = [4, 7, 3, 5];
double[] sizes = [35, 25, 25, 15];
string[] labels = ["North", "East", "South", "West"];
double[,] data = { { 1, 10, 100 }, { 5, 50, 500 } };
SankeyNode[] nodes = [new("Budget"), new("Salaries"), new("Hardware")];
SankeyLink[] links = [new(0, 1, 70), new(0, 2, 30)];
Plt.Create()
.WithSize(1200, 800)
// Line
.AddSubPlot(2, 3, 1, ax => ax.Plot(x, y, s =>
{
s.Color = Css4Colors.DodgerBlue;
s.LineWidth = 2.0;
s.LineStyle = LineStyle.Dashed;
s.Marker = MarkerStyle.Circle; // all 13 shapes supported:
// Circle, Square, Triangle, TriangleDown/Left/Right,
// Diamond, Pentagon, Hexagon, Star, Cross, Plus, None
s.MarkerSize = 6;
s.Smooth = true; // cubic-spline smoothing
s.Label = "Revenue"; // for legend
}))
// Scatter
.AddSubPlot(2, 3, 2, ax => ax.Scatter(x, y, s =>
{
s.Sizes = bubbleSizes; // per-point size
s.C = density; // per-point colormap value
s.ColorMap = ColorMaps.Viridis;
s.Alpha = 0.6;
}))
// Bar
.AddSubPlot(2, 3, 3, ax => ax.Bar(cats, vals, s =>
{
s.Color = Colors.SteelBlue;
s.BarWidth = 0.7;
s.ShowLabels = true;
s.LabelFormat = "0.0";
s.EdgeColor = Colors.Black;
s.Orientation = BarOrientation.Horizontal;
}))
// Pie
.AddSubPlot(2, 3, 4, ax => ax.Pie(sizes, labels, s =>
{
s.Explode = [0, 0.1, 0, 0];
s.AutoPct = "{0:F1}%";
s.StartAngle = 90;
s.Shadow = true;
}))
// Heatmap / contour / surface
.AddSubPlot(2, 3, 5, ax => ax.Heatmap(data, s =>
{
s.ColorMap = ColorMaps.Plasma;
s.Normalizer = new LogNormalizer();
}))
// Sankey
.AddSubPlot(2, 3, 6, ax => ax.Sankey(nodes, links, s =>
{
s.NodeWidth = 24;
s.NodePadding = 14;
s.Iterations = 20; // vertical-relaxation passes
s.LinkColorMode = SankeyLinkColorMode.Gradient;
s.InsideLabels = true; // when NodeWidth is wide enough
}))
.Save("series-properties.svg");After plotting a Candlestick, an OhlcBar or a price line, add:
using MatPlotLibNet;
using MatPlotLibNet.Styling;
double[] close = [.. Enumerable.Range(0, 60).Select(i => 100 + 5 * Math.Sin(i / 6.0) + i * 0.2)];
double[] open = [.. close.Select((c, i) => i == 0 ? c : close[i - 1])];
double[] high = [.. close.Select((c, i) => Math.Max(c, open[i]) + 1)];
double[] low = [.. close.Select((c, i) => Math.Min(c, open[i]) - 1)];
double[] volume = [.. Enumerable.Range(0, 60).Select(i => 1000.0 + i % 7 * 150)];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Candlestick(open, high, low, close)
.Sma(20)
.Ema(50, s => s.Color = Colors.Orange)
.BollingerBands(period: 20, stdDev: 2.0)
.Obv(close, volume)
.Cci(MatPlotLibNet.Indicators.OhlcvBars.Hlc(high, low, close), 20)
.ParabolicSar(high, low))
.Save("indicators.svg");TransferEntropy(source, target) takes a TransferEntropyOptions too (the estimator, the neighbours, the lag, a series to condition on, and a Window and Stride for one value on each bar). 57 of the 59 indicators have a streaming form that follows each new bar: candles.WithStreaming(axes, indicator) attaches any of them to a StreamingCandlestickSeries (see Streaming).
The generic form is ax.Indicator(new MyIndicator(...)). A bounded indicator (Rsi, WilliamsR, Stochastic,
Adx, AroonOscillator and others that pin axes.YAxis.Min/Max to their own fixed scale) does not belong on
this same panel — it would pin the price axes to its own range and erase the candlesticks. Give it its own
subplot instead, the way row 2 of the dashboard below does.
using MatPlotLibNet;
using MatPlotLibNet.Models;
using MatPlotLibNet.Styling;
double[] x = [1, 2, 3, 4, 5, 6, 7, 8];
double[] y = [3, 6, 9, 12.3, 10, 8, 9.5, 11];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.Annotate("Peak", x: 4.0, y: 12.3)
.Annotate("Crash", 6.0, 8.0, arrowX: 7.0, arrowY: 9.5)
.AxHLine(0) // horizontal reference line
.AxVLine(Math.PI, c => c.Color = Colors.Red) // keep the ReferenceLine and change its Value to move it later
.AxHSpan(40, 60) // shaded horizontal band
.AxVSpan(DateTime.UtcNow.AddDays(-7).ToOADate(), DateTime.UtcNow.ToOADate()) // a date span, as OLE dates
.BuyAt(2, 6) // trading signal marker
.SellAt(4, 12.3)
// Threshold — dashed reference line + shaded breach span + optional label, one call
.Threshold(80.0, Orientation.Horizontal, ThresholdBreach.Above,
color: Colors.Red, label: "Alarm"))
.Save("annotations.svg");Threshold(value, orientation, breach, color?, label?) composes an AxHLine/AxVLine at value, a SpanRegion covering the breach zone up to the edge of the plot, and an optional label. It uses existing primitives; there is no new series or renderer. A line across the plot widens the automatic range, as matplotlib's axhline does, so a threshold beyond the data is still drawn; beyond a limit you set, it is not.
An annotation's text takes the theme's text size (Font overrides it). Inside the callback, OffsetX and OffsetY move the
text a number of screen pixels from its point (OffsetY counts downward), VerticalAlignment (Baseline, Center, Top,
Bottom) says which part of the text stands on the point, and AvoidOverlap = true moves it out of the way of the data, the
legend and the other annotations. See Examples.
A shape in data coordinates is a patch you make and add with AddPatch, matplotlib's add_patch: a Rectangle, Polygon,
Arrow, Circle, Ellipse, Wedge or Arc, in MatPlotLibNet.Models.Patches. It is styled through its own properties
(FaceColor, EdgeColor, EdgeWidth, EdgeLineStyle, Alpha, Hatch, HatchColor, Label):
using MatPlotLibNet;
using MatPlotLibNet.Models.Patches;
using MatPlotLibNet.Styling;
double[] x = [0, 2, 4, 6, 8, 10];
double[] y = [1, 3, 2, 5, 4, 6];
Plt.Create()
.AddSubPlot(1, 1, 1, ax => ax
.Plot(x, y)
.AddPatch(new Rectangle(new(2, 1), 4, 3) { Alpha = 0.3, Label = "Window" }) // a corner, a width, a height
.AddPatch(new Circle(new(8, 4), 0.8) { FaceColor = Colors.Tab10Orange }) // a centre and a radius
.AddPatch(new Arrow(new(1, 5), 2, 0) { Width = 0.1 }) // a start and a delta, in data units
.WithLegend())
.Save("patches.svg");A patch is drawn after the spans and before the series, through the axes' transform, counts in the automatic range, and has a
row in the legend when it is labelled. FigureBuilder.AddPatch adds one to the default axes, and Axes.AddPatch returns the
patch it was given.
using MatPlotLibNet;
using MatPlotLibNet.Styling.ColorMaps;
double[] xs = [.. Enumerable.Range(0, 20).Select(i => i / 4.0)];
double[] ys = [.. Enumerable.Range(0, 20).Select(j => j / 4.0)];
var zs = new double[ys.Length, xs.Length];
for (var j = 0; j < ys.Length; j++)
for (var i = 0; i < xs.Length; i++)
zs[j, i] = Math.Sin(xs[i]) * Math.Cos(ys[j]);
Plt.Create()
.WithSize(800, 600)
.With3DRotation() // drag-to-rotate in SVG
.AddSubPlot(1, 1, 1, ax => ax
.Surface(xs, ys, zs, s => s.ColorMap = ColorMaps.Viridis)
.WithCamera(elevation: 35, azimuth: -45, distance: 10)
.WithLighting(dx: 0.3, dy: 0.3, dz: 1.0, ambient: 0.3, diffuse: 0.7)
.SetZLabel("Altitude"))
.Save("surface.svg");distance sets the camera distance used by the perspective matrix. Lower values produce more foreshortening.
Line plot
using MatPlotLibNet;
double[] x = [1, 2, 3, 4, 5];
double[] y = [2, 4, 3, 5, 1];
Plt.Create().Plot(x, y).Save("line.svg");Multi-panel dashboard
using MatPlotLibNet;
using MatPlotLibNet.Models;
double[] t = [.. Enumerable.Range(0, 60).Select(i => (double)i)];
double[] c = [.. t.Select(i => 100 + 5 * Math.Sin(i / 6.0) + i * 0.2)];
double[] o = [.. c.Select((v, i) => i == 0 ? v : c[i - 1])];
double[] h = [.. c.Select((v, i) => Math.Max(v, o[i]) + 1)];
double[] l = [.. c.Select((v, i) => Math.Min(v, o[i]) - 1)];
string[] days = [.. t.Select(i => $"D{i + 1}")];
double[] volume = [.. t.Select(i => 1000 + i % 7 * 150)];
Plt.Create()
.WithSize(1200, 800)
.WithGridSpec(3, 1, heightRatios: [3, 1, 1])
.WithTitle("Q1 — ACME")
.TightLayout()
.AddSubPlot(GridPosition.Single(0, 0), ax => ax.Candlestick(o, h, l, c).Sma(20).BollingerBands(20, 2))
.AddSubPlot(GridPosition.Single(1, 0), ax => ax.Bar(days, volume).SetYLabel("Vol"))
.AddSubPlot(GridPosition.Single(2, 0), ax => ax.Rsi(c, 14).AxHLine(70).AxHLine(30))
.Save("dashboard.svg");Interactive Sankey
using MatPlotLibNet;
using MatPlotLibNet.Models;
using MatPlotLibNet.Models.Series;
SankeyNode[] nodes = [new("Coal"), new("Gas"), new("Power"), new("Homes"), new("Industry")];
SankeyLink[] links = [new(0, 2, 40), new(1, 2, 60), new(2, 3, 45), new(2, 4, 55)];
Plt.Create()
.WithSize(1000, 600)
.WithSankeyHover()
.AddSubPlot(1, 1, 1, ax => ax
.HideAllAxes()
.Sankey(nodes, links, s =>
{
s.Iterations = 20;
s.LinkColorMode = SankeyLinkColorMode.Gradient;
}))
.Save("flow.svg");Nested pie
using MatPlotLibNet;
using MatPlotLibNet.Models;
var departments = new TreeNode
{
Label = "Revenue",
Children =
[
new TreeNode { Label = "Hardware", Children = [new TreeNode { Label = "Laptops", Value = 40 }, new TreeNode { Label = "Phones", Value = 25 }] },
new TreeNode { Label = "Services", Children = [new TreeNode { Label = "Support", Value = 20 }, new TreeNode { Label = "Training", Value = 15 }] },
],
};
Plt.Create()
.WithTitle("Revenue by department → product")
.AddSubPlot(1, 1, 1, ax => ax.NestedPie(departments))
.Save("nested.svg");- Getting Started — installation & first chart
- Chart Types — all 91 series types with examples
-
Styling — themes, colormaps,
PropCycler -
Matplotlib Themes —
MatplotlibClassicvsMatplotlibV2 - Advanced — date axes, math text, animations, GIF, real-time
- Accessibility — SVG semantics, keyboard nav, color-blind palette
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