Skip to content

Data Sources

Data sources publish typed ChartDataFrames; the chart's definition maps their columns to marks. Put a source on the same GameObject as its chart, or on a parent to feed child charts that have no data of their own. Charts resolve the source automatically and have no source or Target Chart assignment field. One source can feed several 2D or 3D charts.

Source

Use it for

MockChartDataSource

Instant generated data for prototypes and demos. Patterns include Random, Linear, Exponential, Logarithmic, Sine, Cosine, TrendingUp, TrendingDown, Seasonal, Stepped, Sparse, RandomWalk, BellCurve, Sawtooth, and GaussianNoise.

ManualChartDataSource

Hand-entered labels, values, series, colors, and reference rules directly in the Inspector.

CsvChartDataSource

CSV, TSV, semicolon-separated files, TextAssets, StreamingAssets, inline text, or absolute paths.

JsonChartDataSource

JSON files or inline JSON, including nested data via root selectors.

GoogleSheetsChartDataSource

A shared Google Sheets URL converted to chart-ready tabular data.

WebChartDataSource

HTTP CSV or JSON endpoints with headers, polling, retry, and backoff.

YahooFinanceChartDataSource

Stock and financial time-series data for line or candlestick charts.

RingBufferChartDataSource

High-throughput live samples, appended efficiently and flushed once per frame.

Mock Data Source

MockChartDataSource is the recommended starting point. Its status card reports published rows and columns above Generate, Start Streaming and Stop Streaming. Use the Shape and Data settings to choose the table form, pattern, series count, points, value range, noise and labels; fields follow the selected shape. The Random, Trending, Seasonal and Bell Curve presets generate immediately.

Label Overflow controls finite label sets: Auto Unique continues with unique labels, Cycle repeats them, and Clamp limits the point count. Start Year appears for calendar presets with Auto Unique. Configure stream rhythm, interval, points per emission and incoming-data behavior in Streaming. Append and prepend continue the pattern from the edge being extended; a deterministic seed replays the same varying sequence. Drip emits one row at irregular gaps averaging the configured interval.

For candlestick charts, generated candles use the previous close as the next open and keep their high and low within the configured value range. Month, quarter, and year label presets use calendar positions when the X axis is Auto or Time; streaming and retention keep those dates stable.

MockChartDataSource mock = gameObject.AddComponent<MockChartDataSource>();
mock.Pattern = SeriesPattern.TrendingUp;
mock.SeriesCount = 3;
mock.PointsPerSeries = 12;
mock.LabelPreset = LabelPreset.MonthsShort;
mock.Regenerate();
mock.StartStreaming();

File and Web Mapping

CSV, JSON, Sheets, Web and Yahoo sources load typed rows and columns. Select the chart host and configure its Marks layers to map those columns to X, Y, Series, Color, Size, labels or OHLC values. The same published table can drive several charts with different mappings.

  • X and Y channels choose position columns. Leave automatic layers unmapped to infer a suitable layout, or bind explicitly when the first numeric column is a measurement rather than X.
  • Category columns supply named positions and category labels. Date columns supply temporal positions; dates without a time zone are read as UTC.
  • A value channel can bind several columns, producing one series per value column for wide tables.
  • A Series channel splits long-form rows by a named series column, or assigns one constant name to a layer.
  • Open, High, Low and Close channels define candlesticks; start and end channels define ranges.
  • Max Rows on a file source limits the rows it loads. Its Preview tab shows the published columns and values before the chart maps them.

Data Source Mental Model

A source answers where values come from, how text or generated samples become typed rows and columns, and when to publish a refresh. The chart definition separately chooses how those columns become marks. This lets Manual, Mock, file, web and ring-buffer sources feed the same chart without owning its presentation.

Choosing a Data Source

Choose the source by ownership and refresh behavior. Use Manual when the scene owns the data, Mock when the real backend is not ready, CSV/JSON for files and exports, Sheets for externally edited tabular data, Web for service-backed dashboards, Yahoo Finance for quick OHLC examples, and RingBuffer for high-frequency live samples.

Individual Data Sources

ManualChartDataSource is best for scene-owned data and Designer handoff. It supports single-series and multi-series values, reference rules, overlay points, overlay rectangles, symbols, colors, gradients, and reusable styling fields.

MockChartDataSource is the recommended starting point for design, demos, and stress tests. It generates patterns with configurable labels, series counts, noise, value ranges, gradients, and streaming rhythms, so a chart can be designed before a production backend exists.

CsvChartDataSource reads separated-value text from a TextAsset, project path, absolute path, StreamingAssets path, or inline string. It can auto-detect the delimiter, header row, and column types, but the inspector can lock those choices down with delimiter, header mode, comment prefix, skip rows, trimming, and file watching options.

JsonChartDataSource is for structured payloads. Use Root Selector when the useful records live inside a larger API response. Nested objects flatten one level with dot notation, which keeps fields such as ohlc.open or metrics.revenue available for normal mapping.

GoogleSheetsChartDataSource converts a published Google Sheets URL into a CSV export URL. Use it when designers or analysts own a sheet outside Unity. The sheet must be published or otherwise reachable by the player/editor, and the gid selects which worksheet tab is read.

WebChartDataSource polls an HTTP or HTTPS endpoint and publishes CSV or JSON responses as typed frames. It supports request headers, JSON root selection, CSV options, polling intervals, cancellation, opt-in edit-mode preview and backoff on transient failures. Map its columns on the chart, rather than on the source.

YahooFinanceChartDataSource loads OHLCV time-series columns from the public Yahoo Finance chart endpoint. Choose a candlestick chart or map the desired price column for a line chart. It is useful for examples and prototypes; use a market-data provider suited to your production requirements through WebChartDataSource.

RingBufferChartDataSource accepts pushed Y or X/Y samples in a fixed-capacity buffer and publishes once per frame. It updates stable-shape values without rebuilding the frame for every sample. Call ClearData() to empty the buffer.

Mapping Concepts

  • Wide format stores one value column per series, such as Month, Core, Pro and Enterprise. Bind the value columns together in a layer's Y channel.
  • Long format stores a series category beside each value, such as Quarter, Region and Revenue. Bind the position, value and Series channels to those columns.
  • Automatic layers infer common shapes, including a date plus a value, a single numeric series by row index, and wide heat-map rows. Bind columns explicitly when the inferred result does not describe your data. The Data status and Marks diagnostics identify missing columns or layers that cannot draw.
  • Date Format and Date Culture control time parsing. Number Culture selects a numeric locale; when left automatic, CSV parsing handles common thousands separators and decimal commas, including semicolon-delimited decimal-comma tables. Missing placeholders such as NA, N/A and null stay empty instead of becoming zero.
  • Choose the candlestick mark and bind Open, High, Low and Close to the source's columns. Change the chart type through the Inspector or Designer to retarget compatible channels; review mappings after a change to a family with different data requirements.
  • Max Rows caps the loaded table before compilation. For very large datasets, combine an appropriate source limit with viewport windows and the renderer's supported LOD or decimation.

Typed Tables and Live Bindings

Use a ChartDataFrame when the data is already a table or several charts need different views of the same rows. Frames contain named number, category, date or Boolean columns and optional validity masks. Readers treat published frames as immutable; a source that owns a frame can overwrite fixed-shape values through its protected streaming API and publish one value-change notification.

Texas demand sample with a rolling line chart beside a bar chart of the latest 24 hours.
The Live Data sample uses an hourly demand replay to drive both a rolling line view and a daily bar view.

ChartDataEncoding maps column names to marks. Its factories cover bars, lines, points, areas, sectors, rectangles and reference rules, including ranged bars and areas. For a one-time chart, pass the frame and encoding to ChartBuilder.AddDataFrame; the named AddBarPlot, AddLinePlot, AddPointPlot and other plot helpers provide the same mapping in a shorter form.

For changing data, retain the binding returned by Chart.Bind and call Update with the next frame. The binding updates compatible marks in place and rebuilds the projection when required. Keep the encoding stable during ordinary refreshes. Dispose the chart when its host no longer uses it.

SetChart(chart) adopts the supplied code-built Chart on Canvas, world-space and UI Toolkit hosts. For a live Chart.Bind binding, bind the Chart that the host displays. For definition-driven charts, pass a ChartDataFrame to host.SetData(frame); pass shapeChanged: false only when columns, row count and categories remain unchanged. ClearData() resumes the bound source, data asset or inline table.

using ChartGuru;

public static class TypedTableExample
{
public static Chart Create(out ChartDataFrameBinding binding)
{
Chart chart = Chart.Create()
.ChartXAxis(axis => axis.Label("Quarter"))
.ChartYAxis(axis => axis.Label("Revenue"))
.Build();

binding = chart.Bind(
Frame(65f, 89f, 78f),
ChartDataEncoding.Bar("Quarter", "Revenue"));
return chart;
}

public static void Refresh(ChartDataFrameBinding binding)
{
binding.Update(Frame(70f, 95f, 82f));
}

private static ChartDataFrame Frame(float q1, float q2, float q3)
{
return new ChartDataFrame(
ChartDataColumns.Category("Quarter", "Q1", "Q2", "Q3"),
ChartDataColumns.Numeric("Revenue", q1, q2, q3));
}
}

Prepare a view of the data before encoding it: Filter keeps matching rows and SortBy orders them. ChartDataTransforms.Calculate adds a derived column, AggregateBy summarizes groups, Rolling adds a moving-window statistic, and FacetBy splits the frame into grouped views. These operations return new frames or facets and preserve the source frame. Choose the resulting columns explicitly when creating the encoding.

Refreshing File and Web Data

File and web sources expose RefreshAsync(CancellationToken) when the application needs to await completion. Bind a loading indicator or status label to RefreshStateChanged; IsRefreshing includes loading, parsing and applying. LastRefreshError contains the most recent sanitized error, and LastRefreshUtc records the last successful completion. State notifications and chart application run on the Unity thread.

A newer refresh supersedes an older request, so a late response cannot replace newer data. Disabling or destroying the source cancels its active work. Treat cancellation separately from an unsuccessful refresh, and unsubscribe application callbacks when their UI is released. A web source can poll through PollIntervalSeconds, with zero meaning a one-shot request; transient failures use backoff. RunInEditMode is opt-in when intentional network traffic in the Editor is needed.

For authentication, supply header values at runtime with SetRuntimeHeader, or choose EnvironmentVariable as the header's value source. Runtime header values are not serialized. Keep credentials out of the serialized literal Value field and out of source-controlled examples.

using System;
using System.Threading;
using System.Threading.Tasks;
using ChartGuru;

public static class WebRefreshExample
{
public static async Task RefreshAsync(
WebChartDataSource source,
string authorizationHeader,
Action<ChartDataRefreshState> showState,
CancellationToken cancellationToken)
{
source.SetRuntimeHeader("Authorization", authorizationHeader);
source.RefreshStateChanged += showState;
try
{
await source.RefreshAsync(cancellationToken);
}
finally
{
source.RefreshStateChanged -= showState;
}
}
}

Configure the source URL and parsing options, place it on the chart or a parent, and map its published columns in the chart definition. Call this method from the application's Unity lifecycle with a cancellation token and status callback. Handle OperationCanceledException separately from unsuccessful refreshes.