### Basic uPlot Chart Setup Source: https://github.com/leeoniya/uplot/blob/master/demos/scales-dir-ori.html Initializes a uPlot chart with default settings and sample data. This serves as a base for demonstrating scale manipulations. ```javascript import uPlot from "../dist/uPlot.esm.js"; let xs = [-3,-2,-1,0,1,2,3,4,5,6]; let vals = [-10,-4,-2,-1,0,2,3,null,5,6]; let vals2 = [-2,2,-2,2,-2,2,-2,2,-2,2]; let data = [ xs, vals, vals2, ]; function chart(opts) { opts = uPlot.assign({ scales: { x: { time: false, }, }, focus: { alpha: 0.3, }, cursor: { lock: true, drag: { x: true, y: true, }, sync: { key: 1, scales: ["x", "y"], }, focus: { prox: 30, } }, series: [ {}, { stroke: "red", fill: "rgba(255,0,0,0.1)", }, { stroke: "blue", fill: "rgba(0,0,255,0.1)" } ], }, opts); return new uPlot(opts, data, document.body); } ``` -------------------------------- ### Basic Points Configuration Source: https://github.com/leeoniya/uplot/blob/master/demos/points.html This example shows a basic uPlot chart with points enabled for a series. It configures the `points.space` and `points.fill` options to customize the appearance of the points. ```javascript let vals1 = randomWalk(50, 180, 0, 100); let data = [ vals1.map((v, i) => i+1), vals1, ]; const opts = { width: 1920, height: 300, title: "Points", scales: { x: { time: false, }, }, series: [ {}, { stroke: "green" }, ], }; let u = new uPlot(opts, data, document.body); ``` -------------------------------- ### State Timeline Chart Example Source: https://github.com/leeoniya/uplot/blob/master/demos/timeline-discrete.html Renders a state timeline chart with duty cycles and transitions. This example uses semantic x-axis width and custom fill/stroke functions to visualize different states. ```javascript let now = incrRound((Date.now() / 1e3), 3600); let statesDisplay = [ {}, { 0: {stroke: "red", fill: "rgba(255, 0, 0, 0.2)"}, 1: {stroke: "green", fill: "rgba(0, 255, 0, 0.2)"}, 2: {stroke: "blue", fill: "rgba(0, 0, 255, 0.2)"}, 3: {stroke: "cyan", fill: "rgba(0, 255, 255, 0.2)"}, }, { 0: {stroke: "red", fill: "rgba(255, 0, 0, 0.2)"}, 4: {stroke: "orange", fill: "rgba(255, 165, 0, 0.4)"}, 5: {stroke: "yellow", fill: "rgba(255, 255, 0, 0.3)"}, }, { 0: {stroke: "red", fill: "rgba(255, 0, 0, 0.2)"}, 4: {stroke: "orange", fill: "rgba(255, 165, 0, 0.4)"}, 5: {stroke: "yellow", fill: "rgba(255, 255, 0, 0.3)"}, }, ]; let frames1 = [ [0,1,2,0,3], [4,5,4,5], [4,null,4,null,4,null,4], ].map(st => [ Array(st.length).fill(undefined).map((v, i) => now - Math.floor((st.length - i) * 3600 * Math.random())).sort(), st, ]); // console.log(frames1); let data1 = uPlot.join(frames1, frames1.map(f => [2,2])); // console.log(data); makeChart({ title: "State timeline, duty cycles & transitions (semantic x width)", mode: 1, fill: (seriesIdx, dataIdx, value) => statesDisplay[seriesIdx][value].fill, stroke: (seriesIdx, dataIdx, value) => statesDisplay[seriesIdx][value].stroke, }, data1); ``` -------------------------------- ### Status History Chart Example Source: https://github.com/leeoniya/uplot/blob/master/demos/timeline-discrete.html Displays a status history chart with periodic samples. This example uses non-semantic x-axis width and demonstrates how to handle null values and specific state transitions. ```javascript let data2 = [ Array(30).fill(undefined).map((v, i) => now - (i+1) * 3600).sort(), Array(30).fill(1), Array(30).fill(4), Array(30).fill(5), ]; data2[1][7] = null; data2[1][25] = 3; data2[2][13] = 0; data2[3][15] = 0; data2[3][19] = null; makeChart({ title: "Status history, periodic samples - (non-semantic x width)", mode: 2, size: [0.9, 100], fill: (seriesIdx, dataIdx, value) => statesDisplay[seriesIdx][value].fill, stroke: (seriesIdx, dataIdx, value) => states ``` -------------------------------- ### Time Range with Start Offset (3-Day) Source: https://github.com/leeoniya/uplot/blob/master/demos/timezones-dst.html Demonstrates a 3-day time range that is explicitly set to start on January 1st, ensuring alignment with the beginning of the year. This is useful for fixed-period reporting. ```javascript let c = initSection('With start offset'); new uPlot( genOpts("3-Day (ensure Jan 1)", 'Etc/UTC'), [[1704240000*msi,1704240000*msi + 25 * 24 * 3600*msi],[0.5,0.5]], c ); ``` -------------------------------- ### Path Gap Clipping with Specific Data Source: https://github.com/leeoniya/uplot/blob/master/demos/path-gap-clip.html This example demonstrates path gap clipping with specific data points. The 'gap' option in 'paths' is set to 10, indicating the threshold for clipping. ```javascript u.add(new uPlot.Series({ label: "Series 2", value: (self, raw, index, data, series) => data[1][index], paths: { gap: 10 } })) ``` -------------------------------- ### Live Updating Chart with Default Pixel Alignment Source: https://github.com/leeoniya/uplot/blob/master/demos/pixel-align.html This example shows a live-updating chart with default pixel alignment enabled. Observe the caterpillar effect on the data points. ```javascript const windowSize = 120000; const interval = 1000; const loop = 1000; const data = [ [], [], [], [], [], ]; function addData() { if (data[0].length == loop) { data[0].shift(); data[1].shift(); data[2].shift(); data[3].shift(); } data[0].push(Date.now()); data[1].push(0 - Math.random()); data[2].push(-1 - Math.random()); data[3].push(-2 - Math.random()); } setInterval(addData, interval); function getSize() { return { width: window.innerWidth - 100, height: window.innerHeight / 3, } } const scales = { x: {}, y: { auto: false, range: [-3.5, 1.5] } }; const opts1 = { title: "pxAlign: 1 (default)", ...getSize(), ms: 1, scales, series: [ {}, { stroke: "red", paths: uPlot.paths.linear(), spanGaps: true, points: { show: true } }, { stroke: "blue", paths: uPlot.paths.spline(), spanGaps: true, points: { show: true } }, { stroke: "purple", paths: uPlot.paths.stepped({align: 1}), spanGaps: true, points: { show: true } }, ], }; let u1 = new uPlot(opts1, data, document.getElementById('chart1')); ``` -------------------------------- ### Multi-group, Multi-bar Chart Example Source: https://github.com/leeoniya/uplot/blob/master/demos/bars-grouped-stacked.html Configures and renders both grouped and stacked bar charts with multiple groups and multiple bars per group. Demonstrates horizontal and vertical orientations. ```javascript let data = [ ["Group A", "Group B", "Group C", "Group D"], [1, 2, 3, 10], [3, 2, 1, 10], [5, 9, 3, 10], ]; let series = [ {}, { label: "Metric 1", fill: "#33BB55", width: 0 }, { label: "Metric 2", fill: "#B56FAB", width: 0 }, { label: "Metric 3", fill: "#BB1133", width: 0 }, ]; makeChart({series, ori: 0, dir: 1}, data); makeChart2({series, ori: 0, dir: 1, stacked: true}, data); document.body.appendChild(document.createElement("div")); makeChart({series, ori: 1, dir: -1}, data); makeChart2({series, ori: 1, dir: -1, stacked: true}, data); document.body.appendChild(document.createElement("div")); ``` -------------------------------- ### ECharts5 Initialization and Configuration Source: https://github.com/leeoniya/uplot/blob/master/bench/ECharts5-sine-stream.html Initializes an ECharts instance and configures it with dataset, tooltip, legend, grid, axes, and series options for a multi-line time-series chart. This setup is for the sine stream visualization. ```javascript let dom = document.getElementById("chart"); let myChart = echarts.init(dom, null, { width: 1920, height: 600 }); let opts = { animation: false, dataset: { source: packData(), dimensions: ["date", "value1", "value2", "value3", "value4", "value5", "value6"] }, tooltip: { trigger: "axis" }, legend: {}, grid: { containLabel: true, left: 0, top: 50, right: 0, bottom: 30 }, xAxis: { type: "time" }, yAxis: [ { type: "value", min: -6, max: 6, }, ], series: [ { name: "sin", z: 0, type: "line", showSymbol: false, lineStyle: { width: 1, color: "red" }, areaStyle: { color: "rgba(255,0,0,0.1)" }, emphasis: { lineStyle: { width: 1 } }, encode: { x: "date", y: "value1" } }, { name: "_1", z: 1, type: "line", showSymbol: false, lineStyle: { width: 1, color: "green" }, areaStyle: { color: "#4caf505e" }, emphasis: { lineStyle: { width: 1 } }, encode: { x: "date", y: "value2" } }, { name: "_2", z: 2, type: "line", showSymbol: false, lineStyle: { width: 1, color: "blue" }, areaStyle: { color: "#0000ff20" }, emphasis: { lineStyle: { width: 1 } }, encode: { x: "date", y: "value3" } }, { name: "_3", z: 3, type: "line", showSymbol: false, lineStyle: { width: 1, color: "orange" }, areaStyle: { color: "#ffa5004f" }, emphasis: { lineStyle: { width: 1 } }, encode: { x: "date", y: "value4" } }, { name: "_4", z: 4, type: "line", showSymbol: false, lineStyle: { width: 1, color: "magenta" }, areaStyle: { color: "#ff00ff20" }, emphasis: { lineStyle: { width: 1 } }, encode: { x: "date", y: "value5" } }, { name: "_5", z: 5, type: "line", showSymbol: false, lineStyle: { width: 1, color: "purple" }, areaStyle: { color: "#80008020" }, emphasis: { lineStyle: { width: 1 } }, encode: { x: "date", y: "value6" } } ] }; myChart.setOption(opts, { notMerge: true }); ``` -------------------------------- ### Chart Creation with Tooltips Plugin Source: https://github.com/leeoniya/uplot/blob/master/demos/tooltips.html This JavaScript code demonstrates how to instantiate a uPlot chart and integrate the custom tooltips plugin. It includes chart configuration, data setup, and periodic chart re-initialization. ```javascript function makeChart(cursorMemo) { console.time('chart'); let opts = { title: "Tooltips", width: 600, height: 400, cursor: cursorMemo?.get(), plugins: [ tooltipsPlugin({ cursorMemo, }), ], scales: { x: { time: false, } }, series: [ {}, { label: "One", stroke: "red", }, { label: "Two", stroke: "blue", show: false, }, ] }; const data = [ [ 1, 2, 3, 4, 5, 6, 7], [40,43,60,65,71,73,80], [18,24,37,55,55,60,63], ]; let u = new uPlot(opts, data, document.body); console.timeEnd('chart'); return u; } // save/restore cursor and tooltip state across re-inits let cursLeft = -10; let cursTop = -10; const cursorMemo = { set: (left, top) => { cursLeft = left; cursTop = top; }, get: () => ({left: cursLeft, top: cursTop}), }; let u = makeChart(cursorMemo); setInterval(() => { u.destroy(); u = makeChart(cursorMemo); }, 2000); ``` -------------------------------- ### Basic Path Gap Clipping Source: https://github.com/leeoniya/uplot/blob/master/demos/path-gap-clip.html This example shows the default behavior of path gap clipping in uPlot. Gaps in the data are automatically handled to prevent lines from connecting across missing data points. ```javascript uPlot.fmtDate('%y-%0m-%0d %H:%M:%S', 1000), uPlot.fmtDate('%H:%M:%S', 1000) ]; let opts = { title: 'Path gap clipping', id: 'ts-chart', class: 'uplot', width: 963, height: 300, series: [ {}, { label: 'Value', spanGaps: true, paths: (self, u, seriesIdx, idx, data, scale, x, y) => { return u.paths.lines(self, u, seriesIdx, idx, data, scale, x, y); } } ], scales: { x: { time: true, range: (self, min, max) => [min - 1e3, max + 1e3] }, y: { range: (self, min, max) => [min - (max - min) * 0.1, max + (max - min) * 0.1] } }, axes: [ { space: 40, side: 3, grid: { show: true }, ticks: { show: true }, font: { size: 12, color: '#fff' }, grid: { width: 1, color: 'rgba(255,255,255,0.1)' } }, { space: 40, side: 5, grid: { show: true }, ticks: { show: true }, font: { size: 12, color: '#fff' }, grid: { width: 1, color: 'rgba(255,255,255,0.1)' } } ], cursor: { drag: { set: null } }, legend: { show: false } }; let data = [ [1578813030000, 1578813090000, 1578813150000, 1578813210000, 1578813270000, 1578813330000, 1578813390000, 1578813450000], [30, null, 35, 32, null, 38, 40, 42] ]; let u = new uPlot(opts, data, document.getElementById('ts-chart')); ``` -------------------------------- ### Chart Initialization and Sync Setup Source: https://github.com/leeoniya/uplot/blob/master/demos/sync-cursor.html Initializes multiple uPlot charts and sets up cursor synchronization using `uPlot.sync()`. Includes event handlers to toggle sync behavior and control mouse event filtering. ```javascript function makeChart(data) { console.time('chart'); let mooSync = uPlot.sync("moo"); let synced = true; let syncBtn = document.getElementById('sync'); syncBtn.onclick = () => { synced = !synced; if (synced) { mooSync.sub(uplot1); mooSync.sub(uplot2); mooSync.sub(uplot3); syncBtn.textContent = 'Disable Sync'; } else { mooSync.unsub(uplot1); mooSync.unsub(uplot2); mooSync.unsub(uplot3); syncBtn.textContent = 'Enable Sync'; } }; let syncedUpDown = true; let syncUpDownBtn = document.getElementById('sync-up-down'); function upDownFilter(type) { return syncedUpDown || (type != "mouseup" && type != "mousedown"); } syncUpDownBtn.onclick = () => { syncedUpDown = !syncedUpDown; if (syncedUpDown) syncUpDownBtn.textContent = 'Disable mouseup/down Sync'; else syncUpDownBtn.textContent = 'Enable mouseup/down Sync'; }; const matchSyncKeys = (own, ext) => own == ext; const cursorOpts = { lock: true, focus: { prox: 16, }, sync: { key: mooSync.key, setSeries: true, match: [matchSyncKeys, matchSyncKeys], filters: { pub: upDownFilter, }, }, }; const opts = { title: "CPU", width: 1920, height: 400, focus: { alpha: 0.3, }, cursor: cursorOpts, series: [ {}, { label: "CPU 1", value: (u, v) => v == null ? "-" : v.toFixed(1) + "%", stroke: "red" }, { label: "CPU 2", value: (u, v) => v == null ? "-" : v.toFixed(1) + "%", stroke: "green" }, { label: "CPU 3", value: (u, v) => v == null ? "-" : v.toFixed(1) + "%", stroke: "blue" } ], axes: [ {}, { values: (u, vals, space) => vals.map(v => +v.toFixed(1) + "%" ) }, ], }; let uplot1 = new uPlot(opts, data[0], document.body); const opts2 = { title: "RAM", width: 940, height: 400, cursor: cursorOpts, series: [ {}, { label: "RAM 1", value: (u, v) => v == null ? "-" : v.toFixed(1) + "%", stroke: "red" }, { label: "RAM 2", value: (u, v) => v == null ? "-" : v.toFixed(1) + "%", stroke: "green" }, { label: "RAM 3", value: (u, v) => v == null ? "-" : v.toFixed(1) + "%", stroke: "blue" } ], axes: [ {}, { values: (u, vals, space) => vals.map(v => +v.toFixed(1) + "%" ) }, ] }; let uplot2 = new uPlot(opts2, data[1], document.body); const opts3 = { title: "TCP", width: 940, height: 400, cursor: cursorOpts, series: [ {}, { label: "TCP 1", value: (u, v) => v == null ? "-" : v.toFixed(1) + " MB", stroke: "red", scale: "mb" }, { label: "TCP 2", value: (u, v) => v == null ? "-" : v.toFixed(1) + " MB", stroke: "green", scale: "mb" }, { label: "TCP 3", value: (u, v) => v == null ? "-" : v.toFixed(1) + " MB", stroke: "blue", scale: "mb" } ], axes: [ {}, { values: (u, vals, space) => vals.map(v => +v.toFixed(1) + " MB" ), scale: "mb" }, ], }; let uplot3 = new uPlot(opts3, data[2], document.body); wait.textContent = "Done!"; console.timeEnd('chart'); /* setTimeout(() => { uplot1.destroy(); delete uplot1; }, 5000); setTimeout(() => { uplot2.destroy(); delete uplot2; }, 10000); */ } ``` -------------------------------- ### Time Range with Start Offset (2-Month) Source: https://github.com/leeoniya/uplot/blob/master/demos/timezones-dst.html Shows a 2-month time range anchored to a specific start date, useful for consistent monthly or quarterly views. The data range is defined by explicit start and end timestamps. ```javascript new uPlot( genOpts("2-Month (ensure Jan 1)", 'Etc/UTC'), [[1722470400*msi,1754006400*msi],[0.5,0.5]], c ); ``` -------------------------------- ### Install uPlot via npm Source: https://context7.com/leeoniya/uplot/llms.txt Install uPlot using npm and import the library and its CSS in your JavaScript modules. ```bash npm install uplot ``` ```javascript import uPlot from 'uplot'; import 'uplot/dist/uPlot.min.css'; ``` -------------------------------- ### Hourly Ticks with DST Transition (Chicago) Source: https://github.com/leeoniya/uplot/blob/master/demos/timezones-dst.html Displays hourly ticks for the America/Chicago timezone during a DST transition. This example is similar to the New York example but uses a different timezone. ```javascript let c = initSection('America/Chicago (Nov 3, 2024: 2am -> 1am)'); let syncKey = null; let tz = 'America/Chicago'; let start = 1730610000; new uPlot( genOpts("1h ticks", tz, syncKey), sliceRange2(start, 0.3), c ); new uPlot( genOpts("2h ticks", tz, syncKey), sliceRange2(start, 0.5), c ); new uPlot( genOpts("3h ticks", tz, syncKey), sliceRange2(start, 1), c ); new uPlot( genOpts("4h ticks", tz, syncKey), sliceRange2(start, 1.5), c ); new uPlot( genOpts("6h ticks", tz, syncKey), sliceRange2(start, 2), c ); new uPlot( genOpts("8h ticks", tz, syncKey), sliceRange2(start, 3), c ); new uPlot( genOpts("12h ticks", tz, syncKey), sliceRange2(start, 4), c ); ``` -------------------------------- ### Chart.js Configuration and Initialization Source: https://github.com/leeoniya/uplot/blob/master/bench/Chart.js4-sine-stream.html Sets up the Chart.js configuration, including data, datasets, and options for scales, animation, and interaction. This configuration is used to render a multi-line chart simulating a data stream. ```javascript let ctx = document.getElementById('chart1').getContext('2d'); let cfg = { data: { datasets: [ { borderColor: 'red', backgroundColor: 'rgba(255,0,0,0.1)', fill: true, data: toObjs(data[0], data[1]), type: 'line', radius: 0, borderWidth: 1 }, { borderColor: 'green', backgroundColor: '#4caf505e', fill: true, data: toObjs(data[0], data[2]), type: 'line', radius: 0, borderWidth: 1 }, { borderColor: 'blue', backgroundColor: '#0000ff20', fill: true, data: toObjs(data[0], data[3]), type: 'line', radius: 0, borderWidth: 1 }, { borderColor: 'orange', backgroundColor: '#ffa5004f', fill: true, data: toObjs(data[0], data[4]), type: 'line', radius: 0, borderWidth: 1 }, { borderColor: 'magenta', backgroundColor: '#ff00ff20', fill: true, data: toObjs(data[0], data[5]), type: 'line', radius: 0, borderWidth: 1 }, { borderColor: 'purple', backgroundColor: '#80008020', fill: true, data: toObjs(data[0], data[6]), type: 'line', radius: 0, borderWidth: 1 } ] }, options: { layout: { padding: { left: 20, right: 40, } }, animation: false, maintainAspectRatio: false, parsing: false, spanGaps: true, normalized: true, interaction: { mode: 'nearest', axis: 'x', intersect: false }, scales: { x: { type: 'time', time: { unit: 'minute', }, stacked: false, ticks: { source: 'auto', maxRotation: 0, autoSkip: true, autoSkipPadding: 75, sampleSize: 1 } }, y: { type: 'linear', stacked: false, min: -6, max: 6, scaleLabel: { display: true, } } } } }; let chart = new Chart(ctx, cfg); ``` -------------------------------- ### Initialize Data and Ranger Options Source: https://github.com/leeoniya/uplot/blob/master/demos/zoom-ranger-xy.html Sets up the initial data array and configuration options for the zoom ranger. The ranger is configured to be narrow and linked to the main chart via a sync key. ```javascript var loop = 100; let data = [ Array(loop), Array(loop), ]; for (var i = 0; i < loop; i++) { let x = 2 * Math.PI * i / loop; let y = Math.sin(x); data[0][i] = x; data[1][i] = y; } let initXmin = 1.0; let initXmax = 4.5; const rangerOpts = { width: 800, height: 100, cursor: { points: { show: false, }, drag: { setScale: false, x: true, y: true, dist: 10, uni: 10 }, sync: { key: "moo", scales: ["x", "y"] } }, legend: { show: false }, scales: { x: { time: false, }, }, series: [ {}, { stroke: "purple", } ], hooks: { ready: [ uRanger => { let left = Math.round(uRanger.valToPos(initXmin, 'x')); let width = Math.round(uRanger.valToPos(initXmax, 'x')) - left; let height = uRanger.bbox.height / devicePixelRatio; uRanger.setSelect({left, width, height}, false); } ] } }; let uRanger = new uPlot(rangerOpts, data, document.body); ``` -------------------------------- ### uPlot Vertical Gradient Stroke (Example 1) Source: https://github.com/leeoniya/uplot/blob/master/demos/gradients.html Applies a vertical gradient stroke to a uPlot series, where the gradient direction is aligned with the y-axis. This example uses negative and positive values. ```javascript let vtGrad = [ [-100, "blue"], // [0, "blue"], [0, "red"], ]; const opts2 = { title: "Scale-aligned gradient strokes (vt)", width: 800, height: 600, legend: { // show: false, markers: { // show: false, stroke: "red", } }, cursor: { points: { fill: (u, seriesIdx) => { let xIdx = u.cursor.idxs[seriesIdx]; if (xIdx != null) { let val = u.data[seriesIdx][xIdx]; for (let i = vtGrad.length - 1; i >= 0; i--) { let stop = vtGrad[i]; if (val >= stop[0]) return stop[1]; } } return "black"; } } }, scales: { x: { time: false, }, }, series: [ {}, { label: "Over/Under", width: 4, stroke: (u, seriesIdx) => { return scaleGradient(u, 'y', 1, vtGrad, true); }, }, ], }; let data2 = [ [20, 30, 40, 50, 60], [-5, 10, -2, -30, 30], ]; let u2 = new uPlot(opts2, data2, document.body); ``` -------------------------------- ### Data Fetching and Chart Initialization Source: https://github.com/leeoniya/uplot/blob/master/bench/Flot.html Fetches data from 'data.json', processes it using prepData, and then renders the chart with a slight delay. Updates a status message during the process. ```javascript let wait = document.getElementById("wait"); wait.textContent = "Fetching data.json (2.07MB)...."; fetch("data.json").then(r => r.json()).then(packed => { wait.textContent = "Rendering..."; let data = prepData(packed); setTimeout(() => makeChart(data), 0); }); ``` -------------------------------- ### Data Preparation and Chart Rendering with Chart.js Source: https://github.com/leeoniya/uplot/blob/master/bench/Chart.js4.html This script fetches data, prepares it for charting, and then renders a real-time chart using Chart.js. It includes helper functions for rounding numbers and processing packed data into a format suitable for Chart.js datasets. The chart displays CPU, RAM, and TCP Out metrics over time. ```javascript function round2(val) { return Math.round(val * 100) / 100; } function round3(val) { return Math.round(val * 1000) / 1000; } function prepData(packed) { console.time('prep'); // epoch,idl,recv,send,read,writ,used,free const numFields = packed[0]; packed = packed.slice(numFields + 1); var cpu = Array(packed.length/numFields); var ram = Array(packed.length/numFields); var tcp = Array(packed.length/numFields); for (let i = 0, j = 0; i < packed.length; i += numFields, j++) { let date = packed[i] * 60 * 1000; cpu[j] = {x: date, y: round3(100 - packed[i+1])}; ram[j] = {x: date, y: round2(100 * packed[i+5] / (packed[i+5] + packed[i+6]))}; tcp[j] = {x: date, y: packed[i+3]}; } console.timeEnd('prep'); return [cpu, ram, tcp] } function makeChart(data) { console.time('chart'); var ctx = document.getElementById('chart1').getContext('2d'); var cfg = { data: { datasets: [ { label: 'CPU', borderColor: 'rgb(255, 99, 132)', data: data[0], type: 'line', radius: 0, fill: false, borderWidth: 1 }, { label: 'RAM', borderColor: 'rgb(54, 162, 235)', data: data[1], type: 'line', radius: 0, fill: false, borderWidth: 1 }, { label: 'TCP Out', borderColor: 'rgb(75, 192, 192)', data: data[2], type: 'line', radius: 0, fill: false, borderWidth: 1 } ] }, options: { animation: false, maintainAspectRatio: false, parsing: false, spanGaps: true, normalized: true, interaction: { mode: 'nearest', axis: 'x', intersect: false }, scales: { x: { type: 'time', stacked: false, ticks: { source: 'auto', maxRotation: 0, autoSkip: true, autoSkipPadding: 75, sampleSize: 1 } }, y: { type: 'linear', stacked: false, scaleLabel: { display: true, labelString: '%' } }, y2: { type: 'linear', stacked: false, position: 'right', scaleLabel: { display: true, labelString: 'MB' } } }, plugins: { decimation: { enabled: true } } } }; var chart = new Chart(ctx, cfg); wait.textContent = "Done!"; console.timeEnd('chart'); } let wait = document.getElementById("wait"); wait.textContent = "Fetching data.json (2.07MB)...."; fetch("data.json").then(r => r.json()).then(packed => { wait.textContent = "Rendering..."; let data = prepData(packed); setTimeout(() => makeChart(data), 0); }); ``` -------------------------------- ### uPlot Chart Initialization with Zoom Plugin Source: https://github.com/leeoniya/uplot/blob/master/demos/zoom-wheel.html Configures and creates a uPlot chart instance, including the wheel zoom plugin. Ensure the DOM element for the chart is available. ```javascript function makeChart() { console.time('chart'); let opts = { title: "Wheel Zoom & Drag", width: 600, height: 400, plugins: [ wheelZoomPlugin({factor: 0.75}) ], scales: { x: { time: false, }, // y: { // auto: false, // } }, series: [ {}, { label: "One", stroke: "red" }, { label: "Two", stroke: "blue" }, ] }; const data = [ [1, 2, 3, 4, 5, 6, 7], [40,43,60,65,71,73,80], [18,24,37,55,55,60,63], ]; let u = new uPlot(opts, data, document.body); console.timeEnd('chart'); } makeChart(); ``` -------------------------------- ### Install uPlot via Script Tag Source: https://context7.com/leeoniya/uplot/llms.txt Include uPlot and its CSS using script tags for direct HTML integration. ```html ``` -------------------------------- ### Unstacked Series Example Source: https://github.com/leeoniya/uplot/blob/master/demos/stacked-series.html Renders a basic unstacked chart with multiple series. Configure series stroke and fill colors. ```javascript const n = null; let opts5 = { width: 400, height: 300, scales: { x: { time: false, } }, series: [ {}, { stroke: 'blue', fill: "rgba(0, 0, 255, 0.3)", }, { stroke: 'green', fill: "rgba(0, 255, 0, 0.3)", }, { stroke: 'orange', fill: "rgba(255, 165, 0, 0.4)", }, { stroke: 'red', fill: 'rgba(255, 0, 0, 0.3)', } ], }; { let data5 = [ [ 0, 1, 2, 3, 4], [ 5, 5, 5, 5, 5], [-10, -10, -10, -10, -10], [ 10, 10, 10, 10, 10], [ -5, -5, -5, -5, -5], ]; new uPlot(uPlot.assign({title: 'unstacked'}, opts5), data5, document.body); ``` -------------------------------- ### Basic Path and Clip Configuration Source: https://github.com/leeoniya/uplot/blob/master/demos/path-gap-clip.html This configuration sets up a basic chart with path and clip options. It defines the canvas dimensions and the series data. ```javascript const data = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ]; new uPlot({ width: 400, height: 300, series: [ {}, // X-axis { // Y-axis // Path and clip options can be configured here } ] }, { scales: { x: { time: false }, y: { range: [0, 10] } }, series: [ { value: (self, raw) => raw }, { value: (self, raw) => raw } ], data: data }); ``` -------------------------------- ### Log10 Y Scale Example Source: https://github.com/leeoniya/uplot/blob/master/demos/log-scales2.html Configures a chart with a base-10 logarithmic y-axis. Useful for visualizing data spanning several orders of magnitude. ```javascript let vals = []; function round6(val) { return Math.round(val * 1e6) / 1e6; } let mags = [-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]; mags.forEach(m => { for (let i = 1; i < 10; i++) vals.push(round6(i * Math.pow(10, m))); }); vals.push(round6(10 * Math.pow(10, mags[mags.length - 1]))); let data = [ vals.map((v, i) => i + 1), vals, ]; const opts = { width: 1600, height: 600, title: "Linear Scale (0.000001 -> 100,000,000)", scales: { x: { time: false, }, }, axes: [ {}, { size: 80, } ], series: [ {}, { stroke: "magenta", }, ], }; let u = new uPlot(opts, data, document.body); const opts2 = { width: 1600, height: 600, title: "Log10 Y Scale (0.000001 -> 100,000,000)", scales: { x: { time: false, }, y: { distr: 3, // log: 10, }, }, axes: [ {}, { size: 80, values: (self, splits) => splits.map(v => v == null ? null : v.toExponential()) } ], series: [ {}, { stroke: "orange", }, ], }; let u2 = new uPlot(opts2, data, document.body); ``` -------------------------------- ### Configure Axis and Grid Options Source: https://github.com/leeoniya/uplot/blob/master/docs/README.md Set basic axis properties such as label visibility, text, font, and grid styling. Use this for standard axis configurations. ```javascript let opts = { axes: [ {}, { show: true, label: "Population", labelSize: 30, labelFont: "bold 12px Arial", font: "12px Arial", gap: 5, size: 50, stroke: "red", grid: { show: true, stroke: "#eee", width: 2, dash: [], }, ticks: { show: true, stroke: "#eee", width: 2, dash: [], size: 10, } } ] } ``` -------------------------------- ### Initialize Plot with a Single Data Point Source: https://github.com/leeoniya/uplot/blob/master/demos/no-data.html Render a plot with just one data point. This can be useful for displaying a single value or a starting point. ```javascript new uPlot({ width: 800, height: 400, title: "1 point (time)", series: [ {}, {stroke: "#000"} ], }, [[1566453600],[1]], document.body); ``` -------------------------------- ### Initialize Time Series Data Source: https://github.com/leeoniya/uplot/blob/master/demos/timezones-dst.html Sets up time and value arrays for a full year, simulating daily data points. Used as a base for generating chart data. ```javascript let ms = .001; let msi = ms * 1e3; // Jan 1 2024 UTC let start = 1704067200 * msi; let times = []; for (let h = 0; h < 366 * 24 + 1; h++) times.push(start + h * 3600 * msi); let values = Array(times.length); for (let i = 0; i < times.length; i++) values[i] = i % 24 == 0 ? 1 : 0; ``` -------------------------------- ### Fetch and Render Data for uPlot Charts Source: https://github.com/leeoniya/uplot/blob/master/demos/stream-data.html Fetches JSON data from a specified URL, processes it using `prepData`, and then renders it using `makeChart`. This is the entry point for the streaming demo. ```javascript let wait = document.getElementById("wait"); wait.textContent = "Fetching data.json (2.07MB)...."; fetch("../bench/data.json").then(r => r.json()).then(packed => { wait.textContent = "Rendering..."; let data = prepData(packed); setTimeout(() => makeChart(data), 0); }); ``` -------------------------------- ### Path Gap Clipping with Data Source: https://github.com/leeoniya/uplot/blob/master/demos/path-gap-clip.html This example shows how to configure uPlot to clip paths where data gaps occur. It requires the 'pathGap' option to be set. ```javascript u.add(new uPlot.Series({ label: "Series 1", value: (self, raw, index, data, series) => data[0][index], paths: { gap: 10 } })) ``` -------------------------------- ### Basic Thin Bars with Stroke and Fill Source: https://github.com/leeoniya/uplot/blob/master/demos/thin-bars-stroke-fill.html Configures thin bars with a red stroke and a semi-transparent red fill. This is a foundational example for styling bars. ```javascript import uPlot from "../dist/uPlot.esm.js"; { let data = [ Array.from({length: 30}, (v, i) => i), Array(30).fill(5), ]; const opts = { title: "Normal", width: 800, height: 200, scales: { x: { time: false, }, }, series: [ {}, { paths: uPlot.paths.bars(), stroke: "red", fill: "rgba(255,0,0,0.2)", }, ], }; let u = new uPlot(opts, data, document.body); } ``` -------------------------------- ### Create Stacked Data and Make Chart Source: https://github.com/leeoniya/uplot/blob/master/demos/bars-grouped-stacked.html Prepares data for stacked charts by calling a `stack` function and then uses `makeChart` to render it. This is a helper function for creating stacked bar charts. ```javascript function makeChart2(opts, data) { let { bands, data: _data } = stack(data, i => false); makeChart(opts, _data, bands); } ```