moonchart

A statistical chart SVG generation library for MoonBit. Supports bar charts, line charts, scatter plots with error bars and multi-series rendering.

chart
plot
svg
visualization
statistics
science
moon add JunJunTnT/moonchart@0.1.2
Download zip
Author
Version
0.1.2
License
Apache-2.0
Last updated
last month
Downloads
29

Dependencies

README

#MoonChart

MoonChart is an SVG charting library written in MoonBit. It produces vector graphics suitable for scientific and statistical plotting — bar charts, line charts, scatter plots, and box plots — with error bars, multi-series rendering, and extensive style controls. Output is an SVG string that can be saved to a file or rendered in a browser via WASM.

Package: JunJunTnT/moonchart Repository: https://github.com/JunJunTnT/moonchart License: Apache-2.0

#Installation

moon add JunJunTnT/moonchart

Then import it in your MoonBit source:

import "JunJunTnT/moonchart"

#Simple Demo

#Performance

MoonChart delivers sub-millisecond SVG rendering via WASM — 500x faster than matplotlib and 20x faster than ECharts on the same input→SVG pipeline.

LibraryMean Render TimeSpeedup (vs matplotlib)
MoonChart98.3 μs501×
ECharts1.97 ms25×
matplotlib49.2 ms

#Quick Start

A minimal bar chart with error bars:

fn main {
let data = [
DataPoint::withErrY(0.0, 45.0, 3.0),
DataPoint::withErrY(1.0, 62.0, 2.5),
]

let result = Chart::new()
.title("Cell Viability")
.xTicks([0.0, 1.0], ["Control", "Treated"])
.xLabel("Condition")
.yLabel("Viability (%)")
.yRange(0.0, 100.0)
.series(Series::bar("24h", data))
.toSvg()

match result {
Ok(svg) => println(svg)
Err(e) => println("Error: \{e}")
}
}

#Chart Types

#Bar Chart

Rectangular bars with optional error bars, grouped or stacked positioning, and bar stroke styling.

let data = [
DataPoint::withErrY(0.0, 45.0, 3.0),
DataPoint::withErrY(1.0, 62.0, 2.5),
]

Series::bar("Group A", data)
.withColor(Color::rgb(0, 122, 184))
.withBarStroke(Color::rgb(0, 80, 140), 1.0)

#Line Chart

Connected points with configurable dash styles, point shapes, and point fill colors.

let data = [
DataPoint::new(0.0, 100.0),
DataPoint::new(1.0, 85.0),
DataPoint::new(2.0, 72.0),
]

Series::line("Trend", data)
.withColor(Color::rgb(212, 57, 57))
.withPointSize(5.0)
.withPointShape(Diamond)
.withLineStyle(Dashed)

#Scatter Plot

Unconnected points with customizable shape, size, and fill color.

let data = [
DataPoint::new(1.2, 2.1),
DataPoint::new(2.3, 3.8),
DataPoint::new(3.1, 5.2),
]

Series::scatter("Group X", data)
.withColor(Color::rgb(0, 122, 184))
.withPointSize(5.0)
.withPointShape(Circle)
.withPointFill(Color::rgb(255, 0, 0))

#Box Plot

Box-and-whisker plot with Q1/Q3 box, median line, whiskers to the furthest points within 1.5x IQR, and outlier markers.

let groups = [
BoxGroup::new(0.0, "Control", [1.2, 2.1, 3.4, 2.8, 1.9, 2.5, 3.0, 2.3]),
BoxGroup::new(1.0, "Treated", [0.8, 1.5, 2.9, 2.1, 1.3, 1.9, 2.4, 1.7]),
]

Series::boxplot("Expression", groups)
.withColor(Color::rgb(0, 122, 184))
.withShowOutliers(true)

#Mixed Charts

Series of different types can be combined in a single chart:

Chart::new()
.series(Series::bar("Experiment", barData))
.series(Series::line("Trend", trendData).withLineStyle(Dashed))

#Feature Matrix

Features below are per-series capabilities — attributes you set on individual Series objects via constructor modifiers.

FeatureBarLineScatterBoxPlot
Error Bars (Y)
Point Shapes (5 types)
Line Styles (4 types)
Custom Color
Point Fill Color
Point Size
Bar Stroke
Outlier Display
Dodged Groups

#Builder API Reference

#Chart Builder

All methods return a new Chart (immutable builder pattern).

MethodDefaultDescription
Chart::new()Create a new chart (chart type is per-series)
.title(text)noneChart title (centered at top)
.size(w, h)600 x 400Canvas dimensions in pixels
.width(w)600Canvas width only
.height(h)400Canvas height only
.xLabel(text)noneX-axis label
.yLabel(text)noneY-axis label
.xTicks(positions, labels)autoX-axis tick positions and display labels
.yRange(min, max)0, 100Y-axis data range
.tickFontSize(size)11Tick label font size (both axes)
.labelFontSize(size)13Axis title font size (both axes)
.yGrid(show)falseY-axis grid lines
.xGrid(show)falseX-axis grid lines
.barWidthRatio(ratio)0.7Bar/box width as fraction of band width (0.0-1.0)
.barGap(gap)0.0Gap between bars in a group, as fraction of bar width
.legend(show, position)autoLegend visibility and position
.legendFontSize(size)12Legend font size
.margin(top, right, bottom, left)40,20,40,50Margins around the plot area
.background(color)whiteChart background color
.fontFamily(family)sans-serifFont family for all text elements
.series(s)Add a single data series
.addSeries(ss)Add multiple series at once
.toSvg()Render chart to an SVG string (Result[String, String])
.save(filename)Render and write SVG to file (Result[Unit, String])
.toOption()Export the internal ChartOption (escape hatch)

#Series Constructors

ConstructorDescription
Series::bar(name, data)Bar chart series
Series::line(name, data)Line chart series
Series::scatter(name, data)Scatter plot series
Series::boxplot(name, groups)Box plot series

#Series Modifiers

MethodDefaultApplies ToDescription
.withColor(color)paletteallOverride series color
.withLineWidth(w)2.0lineLine stroke width
.withPointSize(s)4.0line, scatterData point marker radius
.withPointShape(shape)Circleline, scatterMarker shape
.withLineStyle(style)SolidlineLine dash pattern
.withPointFill(color)series colorline, scatterPoint fill color
.withBarStroke(color, w)nonebarBar border color and width
.withErrorColor(color)blackall with dataError bar color (pass None to inherit series color)
.withErrorLineWidth(w)1.0all with dataError bar line width
.withErrorCapWidth(w)6.0all with dataError bar cap width
.withShowOutliers(show)trueboxplotToggle outlier point display

#Data Types

DataPoint::new(x, y) // Simple (x, y) point
DataPoint::withErrY(x, y, err) // Symmetric error bar: y ± err
DataPoint::withAsymErrY(x, y, lo, hi) // Asymmetric error bar: +hi, -lo

BoxGroup::new(x, label, values) // Raw data for box plot

#Enums

PointShape: Circle | Square | Triangle | Diamond | Cross

LineStyle: Solid | Dashed | Dotted | DashDot

Position: TopLeft | TopCenter | TopRight | BottomLeft | BottomCenter | BottomRight | Left | Right

#Color

Color::rgb(r, g, b) // Opaque color (alpha = 255)
Color::rgba(r, g, b, a) // Color with alpha (0-255)

The default palette is a 6-color colorblind-friendly sequence: blue, orange, green, red, purple, brown. Override per-series with .withColor().

#Axis Configuration

AxisOption::defaultX() // Default X axis (auto-infer ticks from data)
AxisOption::linearY() // Default linear Y axis [0, 100]

#Static API

render(opt : ChartOption) -> Result[String, String] // Render a ChartOption to SVG
saveSvg(filename : String, svg : String) -> Result[Unit, String] // Write SVG string to file

#Running Examples

The examples/ directory contains ready-to-run chart demos. Each example is a standalone MoonBit package that generates an SVG file you can open in any browser.

# Run individual examples moon run examples/bar_chart # Grouped bar chart with error bars → bar_chart.svg moon run examples/line_chart # Multi-series line chart → line_chart.svg moon run examples/scatter_chart # Scatter plot → scatter_chart.svg moon run examples/boxplot_chart # Box plot → boxplot_chart.svg moon run examples/mixed_chart # Bar + line mixed chart → mixed_chart.svg

Each command produces an SVG file in the current directory. Open the generated .svg file in your browser to view the chart.

Tip: All examples use Chart::new()...save("output.svg") to write directly to disk. For programmatic use, replace .save(...) with .toSvg() to get the SVG string.

#Visualization

In the demo/ directory, you can launch a simple chart editor that includes all features of this project and lets you visualize the final SVG image in real time by adjusting parameters.

Run the editor with the following command:

# Start a local HTTP server in the demo directory cd demo python -m http.server 8080

Then open http://localhost:8080 in your browser.

Demo Gallery

#WASM Usage

MoonChart can be compiled to WASM-GC for browser use. A dedicated WASM module is provided at wasm/wasm_api.mbt that exposes a single function:

pub fn render_chart(config_json : String) -> String

It accepts a JSON configuration string and returns an SVG string. The WASM package is configured in wasm/moon.pkg.json with render_chart as the exported function.

Build for WASM:

moon build --target wasm-gc

This enables rendering MoonChart graphics directly in the browser from JavaScript, with all chart types, error bars, and styling options available via a JSON-based API.

#License

Apache 2.0

#
Scale

pub trait Scale {
fn map(Self, Double) -> Double
fn ticks(Self, Int) -> Array[(Double, String)]
fn plotSize(Self) -> Double
}

Trait for coordinate mapping from data space to pixel space.

#
AxisKind

pub enum AxisKind {
Linear(Double, Double)
}

The type of axis scale.

#
AxisOption

pub struct AxisOption {
kind : AxisKind
label : String?
tickPositions : Array[Double]
tickLabels : Array[String]
showTick : Bool
tickCount : Int?
gridLine : Bool
tickFontSize : Double
labelFontSize : Double
tickColor : Color
gridColor : Color
gridWidth : Double
}

Configuration for a single axis (X or Y).

#
AxisOption::defaultX

fn AxisOption::defaultX() -> AxisOption

Create a default X axis (auto-infer ticks from data).

#
AxisOption::linearY

fn AxisOption::linearY() -> AxisOption

Create a default linear Y axis [0, 100].

#
AxisOption::withLabel

fn AxisOption::withLabel(self : AxisOption, label : String) -> AxisOption

Set the axis label for this axis. Returns a new AxisOption.

#
BoxGroup

pub(all) struct BoxGroup {
x : Double
label : String
values : Array[Double]
}

A group of raw data for box plot computation.

#
BoxGroup::new

fn BoxGroup::new(x : Double, label : String, values : Array[Double]) -> BoxGroup

Create a box plot data group.

#
BoxStats

pub(all) struct BoxStats {
min : Double
q1 : Double
median : Double
q3 : Double
max : Double
iqr : Double
lowerFence : Double
upperFence : Double
whiskerLow : Double
whiskerHigh : Double
outliers : Array[Double]
}

Statistics for a single box plot: min, Q1, median, Q3, max, IQR, fences, whiskers, and outliers.

#
CategoryScale

pub struct CategoryScale {
tickPositions : Array[Double]
tickLabels : Array[String]
plotPixels : Double
bandWidth : Double
dataMin : Double
dataMax : Double
}

Category/band scale: maps data x-values to band centers. Supports explicit tick positions/labels and auto-inference.

#
CategoryScale::bandCenter

fn CategoryScale::bandCenter(self : CategoryScale, value : Double) -> Double

Find the band center pixel for a data value. Uses data-coordinate mapping to correctly handle non-uniform tick spacing.

#
CategoryScale::count

fn CategoryScale::count(self : CategoryScale) -> Int

Number of tick positions.

#
CategoryScale::dataRange

fn CategoryScale::dataRange(self : CategoryScale) -> (Double, Double)

Get min/max data range for the category scale.

#
CategoryScale::getBandWidth

fn CategoryScale::getBandWidth(self : CategoryScale) -> Double

Get the band width (for bar width calculations).

#
CategoryScale::label

fn CategoryScale::label(self : CategoryScale, index : Int) -> String

Get tick label by index.

#
CategoryScale::map

fn CategoryScale::map(self : CategoryScale, value : Double) -> Double

Map a data value to pixel using linear interpolation.

#
CategoryScale::new

fn CategoryScale::new(tickPositions : Array[Double], tickLabels : Array[String], plotPixels : Double) -> CategoryScale

Create a category scale from tick positions and labels. When positions is empty, auto-inference is used (handled by layout).

#
CategoryScale::plotSize

fn CategoryScale::plotSize(self : CategoryScale) -> Double

Return the plot size (width or height) in pixels.

#
CategoryScale::position

fn CategoryScale::position(self : CategoryScale, index : Int) -> Double

Get tick position by index.

#
CategoryScale::ticks

fn CategoryScale::ticks(self : CategoryScale, _desired : Int) -> Array[(Double, String)]

Generate tick marks at data-coordinate positions. Tick positions are mapped via data-coordinate interpolation (not index-based).

#
CategoryScale::unmap

fn CategoryScale::unmap(self : CategoryScale, pixel : Double) -> Double

Inverse map: pixel position to data value.

#
Chart

pub struct Chart {
option : ChartOption
}

Chart builder wraps a ChartOption and provides chainable methods.

#
Chart::addSeries

fn Chart::addSeries(self : Chart, ss : Array[Series]) -> Chart

Add multiple series at once.

#
Chart::background

fn Chart::background(self : Chart, color : Color) -> Chart

Set chart background color.

#
Chart::bar

fn Chart::bar() -> Chart

Deprecated: use Chart::new() instead. Chart type is per-series.

#
Chart::barGap

fn Chart::barGap(self : Chart, gap : Double) -> Chart

Set bar gap ratio (0.0~1.0). Gap between bars in a group, as fraction of bar width. Default: 0.0.

#
Chart::barWidthRatio

fn Chart::barWidthRatio(self : Chart, ratio : Double) -> Chart

Set bar width ratio (0.0~1.0). Fraction of band width occupied by bars. Default: 0.7.

#
Chart::fontFamily

fn Chart::fontFamily(self : Chart, family : String) -> Chart

Set font family for all text elements.

#
Chart::height

fn Chart::height(self : Chart, h : Double) -> Chart

Set height only.

#
Chart::labelFontSize

fn Chart::labelFontSize(self : Chart, size : Double) -> Chart

Set axis label (title) font size for both axes.

#
Chart::legend

fn Chart::legend(self : Chart, show : Bool, position : Position) -> Chart

Set legend visibility and position.

#
Chart::legendFontSize

fn Chart::legendFontSize(self : Chart, size : Double) -> Chart

Set legend font size.

#
Chart::line

fn Chart::line() -> Chart

Deprecated: use Chart::new() instead. Chart type is per-series.

#
Chart::margin

fn Chart::margin(self : Chart, top : Double, right : Double, bottom : Double, left : Double) -> Chart

Set chart margins.

#
Chart::new

fn Chart::new() -> Chart

Create a new chart. Chart type is determined per-series via Series::bar/line/scatter.

#
Chart::save

fn Chart::save(self : Chart, filename : String) -> Result[Unit, String]

Render the chart and save to a file (native target only). Returns Ok(()) on success, Err(message) on failure.

#
Chart::scatter

fn Chart::scatter() -> Chart

Deprecated: use Chart::new() instead. Chart type is per-series.

#
Chart::series

fn Chart::series(self : Chart, s : Series) -> Chart

Add a series to the chart.

#
Chart::size

fn Chart::size(self : Chart, w : Double, h : Double) -> Chart

Set chart width and height.

#
Chart::tickFontSize

fn Chart::tickFontSize(self : Chart, size : Double) -> Chart

Set tick font size for both axes.

#
Chart::title

fn Chart::title(self : Chart, t : String) -> Chart

Set chart title.

#
Chart::toOption

fn Chart::toOption(self : Chart) -> ChartOption

Export the internal ChartOption (escape hatch for advanced users).

#
Chart::toSvg

fn Chart::toSvg(self : Chart) -> Result[String, String]

Render the chart to an SVG string. Returns Result with the SVG string on success, error message on failure.

#
Chart::width

fn Chart::width(self : Chart, w : Double) -> Chart

Set width only.

#
Chart::xGrid

fn Chart::xGrid(self : Chart, show : Bool) -> Chart

Enable X-axis grid lines with default color.

#
Chart::xLabel

fn Chart::xLabel(self : Chart, label : String) -> Chart

Set X axis label.

#
Chart::xTicks

fn Chart::xTicks(self : Chart, positions : Array[Double], labels : Array[String]) -> Chart

Set X axis tick positions and labels. positions — data coordinate for each tick. labels — display label for each tick (must match positions length). When positions is empty, ticks are auto-inferred from data.

#
Chart::yGrid

fn Chart::yGrid(self : Chart, show : Bool) -> Chart

Enable Y-axis grid lines with default color.

#
Chart::yLabel

fn Chart::yLabel(self : Chart, label : String) -> Chart

Set Y axis label.

#
Chart::yRange

fn Chart::yRange(self : Chart, min : Double, max : Double) -> Chart

Set Y axis range.

#
ChartOption

pub struct ChartOption {
width : Double
height : Double
margin : Margin
background : Color
title : String?
titleFont : Font
xAxis : AxisOption
yAxis : AxisOption
series : Array[Series]
legend : Bool
legendPosition : Position
legendFontSize : Double
barWidthRatio : Double
barGap : Double
fontFamily : String
}

Complete chart configuration.

#
ChartOption::new

fn ChartOption::new(xAxis : AxisOption, yAxis : AxisOption, series : Array[Series]) -> ChartOption

Create a default ChartOption with given axes and series.

#
ChartType

pub enum ChartType {
Bar
Line
Scatter
BoxPlot
}

The type of chart to render for a series.

#
Color

pub(all) struct Color {
r : Int
g : Int
b : Int
a : Int
}

An RGBA color with components in 0-255 range.

#
Color::rgb

fn Color::rgb(r : Int, g : Int, b : Int) -> Color

Construct an opaque color from RGB (alpha = 255).

#
Color::rgba

fn Color::rgba(r : Int, g : Int, b : Int, a : Int) -> Color

Construct a color with explicit alpha.

#
Color::toHex

fn Color::toHex(self : Color) -> String

Convert color to hex string like "#FF0000".

#
Color::toSvg

fn Color::toSvg(self : Color) -> String

Convert color to SVG "rgb(r,g,b)" or "rgba(r,g,b,a)" string.

#
DataPoint

pub struct DataPoint {
x : Double
y : Double
error_y : ErrorValue?
error_x : ErrorValue?
label : String?
}

A single data point in a series.

#
DataPoint::new

fn DataPoint::new(x : Double, y : Double) -> DataPoint

Create a simple (x, y) data point with no extras.

#
DataPoint::withAsymErrY

fn DataPoint::withAsymErrY(x : Double, y : Double, lo : Double, hi : Double) -> DataPoint

Create a data point with an asymmetric Y error bar.

#
DataPoint::withErrY

fn DataPoint::withErrY(x : Double, y : Double, err : Double) -> DataPoint

Create a data point with a symmetric Y error bar.

#
ErrorValue

pub(all) enum ErrorValue {
Symmetric(Double)
Asymmetric(Double, Double)
}

Represents the error/uncertainty of a data point.

#
ErrorValue::hi

fn ErrorValue::hi(self : ErrorValue) -> Double

Get the upper bound of an error value relative to the data point.

#
ErrorValue::lo

fn ErrorValue::lo(self : ErrorValue) -> Double

Get the lower bound of an error value relative to the data point.

#
Font

pub struct Font {
family : String
size : Double
color : Color
bold : Bool
italic : Bool
}

Font configuration for text elements.

#
Font::default

fn Font::default() -> Font

Default font: 12px sans-serif, black, normal weight.

#
Font::svgAttrs

fn Font::svgAttrs(self : Font) -> String

Build full SVG text style attributes string.

#
Font::title

fn Font::title() -> Font

Create a title font (16px, bold).

#
Layout

pub struct Layout {
canvas : Rect
plot : Rect
xScale : CategoryScale
yScale : LinearScale
dodgeOffsets : Array[Double]
barWidth : Double
}

Layout result: everything renderers need.

#
LineStyle

pub(all) enum LineStyle {
Solid
Dashed
Dotted
DashDot
}

Line dash pattern.

#
LinearScale

pub struct LinearScale {
min : Double
max : Double
plotPixels : Double
}

Linear numeric scale mapping [min, max] to [0, plotPixels].

#
LinearScale::map

fn LinearScale::map(self : LinearScale, value : Double) -> Double

Map a data value to pixel position (linear interpolation).

#
LinearScale::new

fn LinearScale::new(min : Double, max : Double, plotPixels : Double) -> LinearScale

Create a linear scale.

#
LinearScale::plotSize

fn LinearScale::plotSize(self : LinearScale) -> Double

Return the plot size (width or height) in pixels.

#
LinearScale::ticks

fn LinearScale::ticks(self : LinearScale, desired : Int) -> Array[(Double, String)]

Generate nice tick positions using the 1/2/5×10^n algorithm.

#
LinearScale::unmap

fn LinearScale::unmap(self : LinearScale, pixel : Double) -> Double

Inverse map: pixel position to data value.

#
LogScale

pub struct LogScale {
base : Double
min : Double
max : Double
plotPixels : Double
}

Logarithmic scale mapping [min, max] to [0, plotPixels].

#
LogScale::map

fn LogScale::map(self : LogScale, value : Double) -> Double

Map data value to pixel using log mapping.

#
LogScale::new

fn LogScale::new(base : Double, min : Double, max : Double, plotPixels : Double) -> LogScale

Create a logarithmic scale.

#
LogScale::plotSize

fn LogScale::plotSize(self : LogScale) -> Double

Return the plot size (width or height) in pixels.

#
LogScale::ticks

fn LogScale::ticks(self : LogScale, _desired : Int) -> Array[(Double, String)]

Generate ticks at powers of the base.

#
Margin

pub(all) struct Margin {
top : Double
right : Double
bottom : Double
left : Double
}

Chart margin (space around the plot area).

#
Margin::default

fn Margin::default() -> Margin

Default margin: top=40, right=20, bottom=40, left=50.

#
PointShape

pub(all) enum PointShape {
Circle
Square
Triangle
Diamond
Cross
}

Shape of data point markers.

#
Position

pub(all) enum Position {
TopLeft
TopCenter
TopRight
BottomLeft
BottomCenter
BottomRight
Left
Right
}

Position of the legend within the chart.

#
Rect

pub struct Rect {
x : Double
y : Double
w : Double
h : Double
}

A rectangle in pixel space.

#
Rect::bottom

fn Rect::bottom(self : Rect) -> Double

Bottom edge.

#
Rect::centerX

fn Rect::centerX(self : Rect) -> Double

Center X.

#
Rect::centerY

fn Rect::centerY(self : Rect) -> Double

Center Y.

#
Rect::left

fn Rect::left(self : Rect) -> Double

Left edge.

#
Rect::right

fn Rect::right(self : Rect) -> Double

Right edge.

#
Rect::top

fn Rect::top(self : Rect) -> Double

Top edge.

#
Series

pub struct Series {
name : String
chartType : ChartType
data : Array[DataPoint]
color : Color?
lineWidth : Double
pointSize : Double
pointShape : PointShape
lineStyle : LineStyle
pointFill : Color?
barStroke : Color?
barStrokeWidth : Double
errorColor : Color?
errorLineWidth : Double
errorCapWidth : Double
boxGroups : Array[BoxGroup]
showOutliers : Bool
}

A data series: one group of data points with a chart type and style.

#
Series::bar

fn Series::bar(name : String, data : Array[DataPoint]) -> Series

Create a bar chart series.

#
Series::boxplot

fn Series::boxplot(name : String, groups : Array[BoxGroup]) -> Series

Create a box plot series.

#
Series::line

fn Series::line(name : String, data : Array[DataPoint]) -> Series

Create a line chart series.

#
Series::scatter

fn Series::scatter(name : String, data : Array[DataPoint]) -> Series

Create a scatter chart series.

#
Series::withBarStroke

fn Series::withBarStroke(self : Series, c : Color, w : Double) -> Series

Set bar stroke color and width.

#
Series::withColor

fn Series::withColor(self : Series, c : Color) -> Series

Set a custom color for this series.

#
Series::withErrorCapWidth

fn Series::withErrorCapWidth(self : Series, w : Double) -> Series

Set error bar cap width.

#
Series::withErrorColor

fn Series::withErrorColor(self : Series, c : Color?) -> Series

Set error bar color (None to inherit series color).

#
Series::withErrorLineWidth

fn Series::withErrorLineWidth(self : Series, w : Double) -> Series

Set error bar line width.

#
Series::withLineStyle

fn Series::withLineStyle(self : Series, s : LineStyle) -> Series

Set line style (dashed, dotted, etc.).

#
Series::withLineWidth

fn Series::withLineWidth(self : Series, w : Double) -> Series

Set line width for this series.

#
Series::withPointFill

fn Series::withPointFill(self : Series, c : Color) -> Series

Set point fill color.

#
Series::withPointShape

fn Series::withPointShape(self : Series, s : PointShape) -> Series

Set point shape for this series.

#
Series::withPointSize

fn Series::withPointSize(self : Series, s : Double) -> Series

Set point size for this series.

#
Series::withShowOutliers

fn Series::withShowOutliers(self : Series, show : Bool) -> Series

Set whether to show outlier points for box plots.

#
DEFAULT_ERROR_CAP_WIDTH

let DEFAULT_ERROR_CAP_WIDTH : Double

Default error bar cap width (horizontal crossbar).

#
DEFAULT_ERROR_LINE_WIDTH

let DEFAULT_ERROR_LINE_WIDTH : Double

Default error bar line width.

#
DEFAULT_HEIGHT

let DEFAULT_HEIGHT : Double

Default chart height in pixels.

#
DEFAULT_LINE_WIDTH

let DEFAULT_LINE_WIDTH : Double

Default line width for line charts.

#
DEFAULT_POINT_SIZE

let DEFAULT_POINT_SIZE : Double

Default point marker radius for scatter/line charts.

#
DEFAULT_WIDTH

let DEFAULT_WIDTH : Double

Default chart width in pixels.

#
axisColor

fn axisColor() -> Color

Default axis line color.

#
axisTitleFont

fn axisTitleFont() -> Font

Default axis title font.

#
backgroundColor

fn backgroundColor() -> Color

Background color.

#
circle

fn circle(cx~ : Double, cy~ : Double, r~ : Double, fill~ : String, stroke~ : String, strokeWidth~ : Double) -> String

Generate an SVG circle element.

#
computeBoxStats

fn computeBoxStats(values : Array[Double]) -> BoxStats

Compute box plot statistics (five-number summary, IQR, fences, whiskers, outliers) from an array of values.

#
computeLayout

fn computeLayout(opt : ChartOption) -> Result[Layout, String]

Compute the layout from a ChartOption. Returns Result: Ok(Layout) on success, Err(message) on failure.

#
formatPoints

fn formatPoints(pts : Array[(Double, Double)]) -> String

Format a sequence of (x, y) points into a polyline points string.

#
legendFont

fn legendFont() -> Font

Legend item font.

#
line

fn line(x1~ : Double, y1~ : Double, x2~ : Double, y2~ : Double, stroke~ : String, strokeWidth~ : Double) -> String

Generate an SVG line element.

#
palette

fn palette(index : Int) -> Color

6-color colorblind-friendly palette.

#
polyline

fn polyline(points~ : String, stroke~ : String, strokeWidth~ : Double, fill~ : String) -> String

Generate an SVG polyline element for line charts.

#
rect

fn rect(x~ : Double, y~ : Double, w~ : Double, h~ : Double, fill~ : String, stroke~ : String, strokeWidth~ : Double) -> String

Generate an SVG rect element.

#
render

fn render(opt : ChartOption) -> Result[String, String]

Render a ChartOption directly to SVG (static entry point).

#
renderBars

fn renderBars(layout : Layout, opt : ChartOption, seriesIndex : Int) -> String

Render all bar series into SVG strings. Parameters: layout - chart layout, opt - chart options, seriesIndex - index of the series to render.

#
renderBoxplot

fn renderBoxplot(layout : Layout, opt : ChartOption, seriesIndex : Int) -> String

Render a box plot series (Q1/Q3 box, median line, whiskers with caps, and outliers) into SVG. Parameters: layout - chart layout config, opt - full chart options, seriesIndex - index of the series to render.

#
renderErrorBars

fn renderErrorBars(layout : Layout, opt : ChartOption, seriesIndex : Int) -> String

Render error stems and caps for a series, matching bar, box, line, or scatter chart positions. Parameters: layout, chart options, and the series index within the options.

#
renderLegend

fn renderLegend(layout : Layout, opt : ChartOption) -> String

Render the chart legend.

#
renderLine

fn renderLine(layout : Layout, opt : ChartOption, seriesIndex : Int) -> String

Render a line series into SVG given layout, chart options, and series index.

#
renderScatter

fn renderScatter(layout : Layout, opt : ChartOption, seriesIndex : Int) -> String

Render a scatter series into SVG from the given layout, chart options, and series index.

#
renderTitle

fn renderTitle(opt : ChartOption) -> String

Render the chart title (centered at top). opt provides the title text and chart dimensions.

#
renderXAxis

fn renderXAxis(layout : Layout, opt : ChartOption) -> String

Render the X-axis (bottom of plot area). layout provides plot and scale geometry; opt provides axis styling.

#
renderYAxis

fn renderYAxis(layout : Layout, opt : ChartOption) -> String

Render the Y-axis (left side of plot area). layout provides plot and scale geometry; opt provides axis styling.

#
rotatedText

fn rotatedText(x~ : Double, y~ : Double, content~ : String, font~ : Font) -> String

Generate a rotated SVG text element (for Y axis labels).

#
saveSvg

fn saveSvg(filename : String, svg : String) -> Result[Unit, String]

Save an SVG string to a file in the current directory. Uses @fs.write_string_to_file from moonbitlang/x. Returns Ok(()) on success, Err(message) on failure.

#
seriesColor

fn seriesColor(index : Int) -> Color

Get the color for a series by its index (0-based).

#
svgClose

fn svgClose() -> String

Generate the SVG document closing.

#
svgOpen

fn svgOpen(width~ : Double, height~ : Double, bg~ : String) -> String

Generate the SVG document opening.

#
text

fn text(x~ : Double, y~ : Double, content~ : String, font~ : Font, textAnchor~ : String) -> String

Generate an SVG text element.

#
tickFont

fn tickFont() -> Font

Default axis tick label font.

#
titleFont

fn titleFont() -> Font

Default title font.

#
xmlEscape

fn xmlEscape(s : String) -> String

Escape XML special characters in text content.