TinyMaterialDesign
Loading...
Searching...
No Matches
LineChart.h
Go to the documentation of this file.
1#pragma once
2#include <math.h>
3#include <stdio.h>
4
5#include <algorithm>
6#include <functional>
7#include <string>
8#include <vector>
9
10#include "TinyGPU/Color/RGB565.h"
11#include "TinyGPU/Color/RGB666.h"
12#include "TinyGPU/Color/RGB888.h"
13#include "TinyMaterialDesign/Core/Widget.h"
14
15namespace tinymd {
16
17/// One data series of a LineChart.
18template <typename RGB_T>
20 /// The values, oldest/leftmost first. NaN values break the line.
21 std::vector<float> values;
22 RGB_T color;
23 /// Line width in pixels.
24 uint8_t width = 2;
25 bool visible = true;
26 /// Draw the line dashed (e.g. to tell apart series of similar colors).
27 bool dashed = false;
28 /// Name in the legend; series without a label are not listed.
29 std::string label;
30};
31
32/// A horizontal line at a fixed value, e.g. a threshold or a target.
33template <typename RGB_T>
35 float value = 0.0f;
36 RGB_T color;
37 bool dashed = true;
38};
39
40/**
41 * @brief Line chart with one or more series, a vertical value scale with
42 * round-numbered grid lines, optional reference lines, and an optional card
43 * frame with a title and a footer line.
44 *
45 * LineChart<RGB565> chart(Bounds(8, 8, 224, 140), "Temperature");
46 * int s = chart.addSeries(colorFromHex<RGB565>(0x06B6D4));
47 * chart.addReferenceLine(25.0f, colorFromHex<RGB565>(0xF59E0B));
48 * chart.setValues(s, readings); // std::vector<float>
49 * screen.invalidate(); // data changed outside a gesture
50 *
51 * Y axis: automatic (the range of all visible values, snapped outward to a
52 * 1/2/5 x 10^n step - see setGridCount()) or fixed via setYRange(); the grid
53 * values can also be given explicitly via setGridValues().
54 *
55 * X axis: by default the points of each series are stretched over the full
56 * plot width. setVisiblePoints(n) instead gives every point a fixed spacing
57 * of width / (n - 1) with the newest point at the right edge - a rolling
58 * "oscilloscope" trace that scrolls in from the right as points are added.
59 *
60 * Series with more points than the plot has pixel columns are drawn as a
61 * min/max envelope per column, so peaks are never lost however many points
62 * there are. All drawing goes through clipped primitives, so the chart works
63 * inside a scrolling Container.
64 */
65template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
66class LineChart : public Widget<RGB_T> {
67 public:
68 LineChart() = default;
69 explicit LineChart(Bounds bounds, const char* title = nullptr) {
70 this->bounds = bounds;
71 if (title != nullptr) title_ = title;
72 }
73
74 /// Draws a rounded card behind the chart (default) - set to false to draw
75 /// the chart directly on the screen background.
76 bool card = true;
77
78 void setTitle(const char* title) { title_ = title; }
79 /// One line of text below the plot, e.g. a summary of the values.
80 void setFooter(const char* footer) { footer_ = footer; }
81
82 /// Adds a series and returns its index.
83 int addSeries(RGB_T color, uint8_t width = 2) {
84 ChartSeries<RGB_T> s;
85 s.color = color;
86 s.width = width;
87 series_.push_back(s);
88 return static_cast<int>(series_.size()) - 1;
89 }
90
91 int seriesCount() const { return static_cast<int>(series_.size()); }
92
93 /// Name of the series in the legend (drawn above the footer when at least
94 /// one series has a label).
95 void setSeriesLabel(int index, const char* label) { series(index).label = label != nullptr ? label : ""; }
96 /// Draw the series dashed.
97 void setSeriesDashed(int index, bool dashed) { series(index).dashed = dashed; }
98 ChartSeries<RGB_T>& series(int index) { return series_[static_cast<size_t>(index)]; }
99
100 /// Replaces the values of the series `index`.
101 void setValues(int index, const std::vector<float>& values) { series(index).values = values; }
102 void setValues(int index, const float* values, size_t count) {
103 series(index).values.assign(values, values + count);
104 }
105
106 /// Appends one value to the series `index`, dropping the oldest value once
107 /// the series holds `maxPoints` values (0 = unlimited).
108 void addValue(int index, float value, size_t maxPoints = 0) {
109 std::vector<float>& v = series(index).values;
110 if (maxPoints > 0 && v.size() >= maxPoints) v.erase(v.begin(), v.begin() + (v.size() - maxPoints + 1));
111 v.push_back(value);
112 }
113
114 /// Adds a horizontal reference line and returns its index.
115 int addReferenceLine(float value, RGB_T color, bool dashed = true) {
116 ChartReferenceLine<RGB_T> line;
117 line.value = value;
118 line.color = color;
119 line.dashed = dashed;
120 lines_.push_back(line);
121 return static_cast<int>(lines_.size()) - 1;
122 }
123 void setReferenceLine(int index, float value) { lines_[static_cast<size_t>(index)].value = value; }
124
125 /// Fixes the value range of the Y axis.
126 void setYRange(float minValue, float maxValue) {
127 fixedRange_ = true;
128 minY_ = minValue;
129 maxY_ = maxValue;
130 }
131 /// Goes back to an automatic Y range.
132 void clearYRange() { fixedRange_ = false; }
133
134 /// Approximate number of grid lines of the automatic scale (default 4).
135 void setGridCount(int count) { gridCount_ = std::max(1, count); }
136 /// Uses exactly these grid values (labelled) instead of the automatic ones.
137 void setGridValues(const std::vector<float>& values) { gridValues_ = values; }
138
139 /// Fixed spacing for `count` points with the newest at the right edge (see
140 /// the class comment); 0 stretches all points over the width (default).
141 void setVisiblePoints(int count) { visiblePoints_ = count; }
142
143 /// Formats a value of an axis label.
144 using AxisFormatter = std::function<void(float value, char* buf, size_t len)>;
145
146 /**
147 * Labels the X axis: the left edge of the plot is `first`, the right edge
148 * `last`, with `ticks` (>= 2) evenly spaced labels and tick marks including
149 * both edges. The values only label the axis - the points are still placed
150 * as described in the class comment. Example for a rolling minute:
151 * chart.setXAxis(-60, 0, 4, [](float v, char* b, size_t n) {
152 * snprintf(b, n, v == 0 ? "now" : "%.0fs", v);
153 * });
154 */
155 void setXAxis(float first, float last, int ticks = 3, AxisFormatter format = nullptr) {
156 xAxis_ = true;
157 xFirst_ = first;
158 xLast_ = last;
159 xTicks_ = std::max(2, ticks);
160 xFormat_ = std::move(format);
161 }
162 /// Removes the X axis labels.
163 void clearXAxis() { xAxis_ = false; }
164
165 void draw(tinygpu::ISurface<RGB_T>& target) override {
166 const MaterialTheme<RGB_T>& t = this->theme();
167 const Bounds& b = this->bounds;
168 const RGB_T background = card ? t.colors.surface : t.colors.background;
169 if (card) {
170 const size_t radius = toPx(t.shape.large);
171 target.fillRoundRect(toPx(b.x), toPx(b.y), toPx(b.w), toPx(b.h), radius, t.colors.surface);
172 target.drawRoundRect(toPx(b.x), toPx(b.y), toPx(b.w), toPx(b.h), radius, t.colors.outline);
173 }
174 const int32_t pad = card ? 8 : 0;
175 tinygpu::IFont<RGB_T>& small = *t.typography.label;
176 tinygpu::IFont<RGB_T>& body = *t.typography.body;
177 int32_t top = b.y + (card ? 6 : 0);
178 if (!title_.empty()) {
179 text(target, body, b.x + pad, top, title_.c_str(), t.colors.onSurface, background);
180 top += static_cast<int32_t>(body.getHeight(1)) + 8;
181 } else {
182 top += 4;
183 }
184 int32_t bottom = b.bottom() - (card ? 6 : 0);
185 if (!footer_.empty()) {
186 bottom -= static_cast<int32_t>(small.getHeight(1));
187 text(target, small, b.x + pad, bottom, footer_.c_str(), t.colors.onSurfaceVariant, background);
188 bottom -= 6;
189 } else {
190 bottom -= 4;
191 }
192 if (hasLegend()) {
193 bottom -= static_cast<int32_t>(small.getHeight(1));
194 drawLegend(target, small, b.x + pad, b.right() - pad, bottom, background);
195 bottom -= 6;
196 }
197 if (xAxis_) bottom -= static_cast<int32_t>(small.getHeight(1)) + 6; // room for the labels
198
199 // value range
200 double lo = minY_, hi = maxY_;
201 if (!fixedRange_) {
202 lo = INFINITY;
203 hi = -INFINITY;
204 for (const ChartSeries<RGB_T>& s : series_) {
205 if (!s.visible) continue;
206 for (float v : s.values) {
207 if (!isfinite(v)) continue;
208 lo = std::min<double>(lo, v);
209 hi = std::max<double>(hi, v);
210 }
211 }
212 if (!isfinite(lo)) {
213 lo = 0.0;
214 hi = 1.0;
215 }
216 }
217 if (hi - lo < 1e-9) {
218 lo -= 0.5;
219 hi += 0.5;
220 }
221
222 // grid values and their labels
223 std::vector<double> grid;
224 double step = 0;
225 if (!gridValues_.empty()) {
226 for (float v : gridValues_) grid.push_back(v);
227 step = grid.size() > 1 ? fabs(grid[1] - grid[0]) : hi - lo;
228 } else {
229 step = niceStep(hi - lo, gridCount_);
230 if (!fixedRange_) {
231 lo = floor(lo / step) * step;
232 hi = ceil(hi / step) * step;
233 }
234 for (double v = ceil(lo / step - 1e-9) * step; v <= hi + step * 1e-6; v += step) grid.push_back(v);
235 }
236 if (step <= 0) step = 1;
237 int decimals = static_cast<int>(-floor(log10(step)));
238 decimals = std::min(4, std::max(0, decimals));
239 char buf[24];
240 int32_t labelW = 0;
241 for (double v : grid) {
242 label(buf, sizeof(buf), v, step, decimals);
243 labelW = std::max<int32_t>(labelW, static_cast<int32_t>(small.measureTextWidth(buf)));
244 }
245
246 const int32_t left = b.x + pad + labelW + 4;
247 const int32_t right = b.right() - pad;
248 const int32_t plotW = right - left;
249 const int32_t plotH = bottom - top;
250 if (plotW < 4 || plotH < 4) return;
251 auto yOf = [&](double v) {
252 v = std::min(std::max(v, lo), hi);
253 return top + plotH - static_cast<int32_t>((v - lo) / (hi - lo) * plotH);
254 };
255
256 for (double v : grid) {
257 if (v < lo - step * 1e-6 || v > hi + step * 1e-6) continue;
258 const int32_t y = yOf(v);
259 if (fabs(v) < step * 1e-6) {
260 target.fillRect(toPx(left), toPx(y), toPx(plotW), 1, t.colors.onSurfaceVariant);
261 } else {
262 dashedLine(target, left, right, y, t.colors.outline, 3, 3);
263 }
264 label(buf, sizeof(buf), v, step, decimals);
265 text(target, small, left - 4 - static_cast<int32_t>(small.measureTextWidth(buf)),
266 y - static_cast<int32_t>(small.getHeight(1)) / 2, buf, t.colors.onSurfaceVariant, background);
267 }
268 target.fillRect(toPx(left), toPx(top), 1, toPx(plotH), t.colors.outline);
269 if (xAxis_) drawXAxis(target, small, left, right, top + plotH, background);
270
271 for (const ChartSeries<RGB_T>& s : series_) {
272 if (s.visible) drawSeries(target, s, left, right, yOf);
273 }
274 for (const ChartReferenceLine<RGB_T>& line : lines_) {
275 const int32_t y = yOf(line.value);
276 if (line.dashed) {
277 dashedLine(target, left, right, y, line.color, 6, 4);
278 dashedLine(target, left, right, y + 1, line.color, 6, 4);
279 } else {
280 target.fillRect(toPx(left), toPx(y), toPx(plotW), 2, line.color);
281 }
282 }
283 }
284
285 private:
286 std::string title_;
287 std::string footer_;
288 std::vector<ChartSeries<RGB_T>> series_;
289 std::vector<ChartReferenceLine<RGB_T>> lines_;
290 std::vector<float> gridValues_;
291 bool fixedRange_ = false;
292 float minY_ = 0.0f;
293 float maxY_ = 1.0f;
294 int gridCount_ = 4;
295 int visiblePoints_ = 0;
296 bool xAxis_ = false;
297 float xFirst_ = 0, xLast_ = 0;
298 int xTicks_ = 3;
299 AxisFormatter xFormat_;
300
301 /// One pixel column of a series: the first/last/min/max y of its points.
302 struct Column {
303 int32_t x = 0, first = 0, last = 0, min = 0, max = 0;
304 };
305
306 /// Tick marks and labels below the plot (y = bottom of the plot).
307 void drawXAxis(tinygpu::ISurface<RGB_T>& target, tinygpu::IFont<RGB_T>& font, int32_t left, int32_t right,
308 int32_t y, RGB_T background) {
309 const MaterialTheme<RGB_T>& t = this->theme();
310 char buf[16];
311 for (int i = 0; i < xTicks_; ++i) {
312 const int32_t x = left + static_cast<int32_t>(static_cast<int64_t>(right - left) * i / (xTicks_ - 1));
313 target.fillRect(toPx(x), toPx(y), 1, 3, t.colors.outline);
314 const float v = xFirst_ + (xLast_ - xFirst_) * i / (xTicks_ - 1);
315 if (xFormat_) {
316 xFormat_(v, buf, sizeof(buf));
317 } else {
318 snprintf(buf, sizeof(buf), "%g", v);
319 }
320 const int32_t w = static_cast<int32_t>(font.measureTextWidth(buf));
321 // the outer labels stay inside the plot, the others are centered
322 const int32_t lx = i == 0 ? x : i == xTicks_ - 1 ? x - w : x - w / 2;
323 text(target, font, lx, y + 4, buf, t.colors.onSurfaceVariant, background);
324 }
325 }
326
327 bool hasLegend() const {
328 for (const ChartSeries<RGB_T>& s : series_) {
329 if (!s.label.empty()) return true;
330 }
331 return false;
332 }
333
334 /// One line: a short (dashed) stroke in the color of each series and its
335 /// label, as many as fit.
336 void drawLegend(tinygpu::ISurface<RGB_T>& target, tinygpu::IFont<RGB_T>& font, int32_t x, int32_t right,
337 int32_t y, RGB_T background) {
338 const int32_t mid = y + static_cast<int32_t>(font.getHeight(1)) / 2;
339 for (const ChartSeries<RGB_T>& s : series_) {
340 if (s.label.empty() || !s.visible) continue;
341 const int32_t w = 14 + 4 + static_cast<int32_t>(font.measureTextWidth(s.label.c_str()));
342 if (x + w > right) break;
343 if (s.dashed) {
344 dashedLine(target, x, x + 14, mid, s.color, 4, 2);
345 dashedLine(target, x, x + 14, mid + 1, s.color, 4, 2);
346 } else {
347 target.fillRect(toPx(x), toPx(mid), 14, 2, s.color);
348 }
349 text(target, font, x + 18, y, s.label.c_str(), s.color, background);
350 x += w + 10;
351 }
352 }
353
354 template <typename YOf>
355 void drawSeries(tinygpu::ISurface<RGB_T>& target, const ChartSeries<RGB_T>& s, int32_t left, int32_t right,
356 YOf yOf) {
357 const size_t n = s.values.size();
358 if (n == 0) return;
359 const int32_t plotW = right - left;
360 bool pen = false; // a previous column exists that the line continues from
361 bool open = false; // `col` holds data
362 Column col, prev;
363 int32_t dashCounter = 0;
364 int32_t* dash = s.dashed ? &dashCounter : nullptr;
365 auto flush = [&]() {
366 if (!open) return;
367 if (col.max > col.min) line(target, col.x, col.min, col.x, col.max, s.color, s.width, dash);
368 if (pen) {
369 line(target, prev.x, prev.last, col.x, col.first, s.color, s.width, dash);
370 } else if (col.max == col.min) {
371 line(target, col.x, col.first, col.x, col.first, s.color, s.width, dash);
372 }
373 prev = col;
374 pen = true;
375 open = false;
376 };
377 for (size_t i = 0; i < n; ++i) {
378 int32_t x;
379 if (visiblePoints_ > 1) {
380 x = right - static_cast<int32_t>(static_cast<double>(n - 1 - i) * plotW / (visiblePoints_ - 1));
381 if (x < left) continue;
382 } else {
383 x = n > 1 ? left + static_cast<int32_t>(static_cast<double>(plotW) * i / (n - 1)) : left;
384 }
385 const float v = s.values[i];
386 if (!isfinite(v)) {
387 flush();
388 pen = false;
389 continue;
390 }
391 const int32_t y = yOf(v);
392 if (open && x != col.x) flush();
393 if (!open) {
394 col.x = x;
395 col.first = col.last = col.min = col.max = y;
396 open = true;
397 } else {
398 col.last = y;
399 col.min = std::min(col.min, y);
400 col.max = std::max(col.max, y);
401 }
402 }
403 flush();
404 }
405
406 /// Bresenham line drawn with fillRect, so it honors the clip rectangle.
407 /// With `dash`, only 5 of every 9 pixels are drawn (the counter continues
408 /// over the segments of a series, so the pattern does not restart).
409 static void line(tinygpu::ISurface<RGB_T>& target, int32_t x0, int32_t y0, int32_t x1, int32_t y1,
410 RGB_T color, uint8_t width, int32_t* dash = nullptr) {
411 const int32_t w = width == 0 ? 1 : width;
412 const int32_t half = w / 2;
413 const int32_t dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
414 const int32_t dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
415 int32_t err = dx + dy;
416 while (true) {
417 const bool on = dash == nullptr || ((*dash)++ % 9) < 5;
418 if (on && x0 - half >= 0 && y0 - half >= 0) target.fillRect(toPx(x0 - half), toPx(y0 - half), toPx(w), toPx(w), color);
419 if (x0 == x1 && y0 == y1) break;
420 const int32_t e2 = 2 * err;
421 if (e2 >= dy) {
422 err += dy;
423 x0 += sx;
424 }
425 if (e2 <= dx) {
426 err += dx;
427 y0 += sy;
428 }
429 }
430 }
431
432 static void dashedLine(tinygpu::ISurface<RGB_T>& target, int32_t x0, int32_t x1, int32_t y, RGB_T color,
433 int32_t dash, int32_t gap) {
434 for (int32_t x = x0; x < x1; x += dash + gap) {
435 const int32_t end = std::min(x + dash, x1);
436 target.fillRect(toPx(x), toPx(y), toPx(end - x), 1, color);
437 }
438 }
439
440 static void text(tinygpu::ISurface<RGB_T>& target, tinygpu::IFont<RGB_T>& font, int32_t x, int32_t y,
441 const char* str, RGB_T color, RGB_T background) {
442 font.drawText(target, static_cast<int16_t>(x), static_cast<int16_t>(y), str, color, background, false);
443 }
444
445 /// Round step (1, 2, 5 x 10^n) giving about `targetTicks` grid lines.
446 static double niceStep(double range, int targetTicks) {
447 const double raw = range / targetTicks;
448 const double mag = pow(10.0, floor(log10(raw)));
449 const double norm = raw / mag;
450 const double nice = norm < 1.5 ? 1.0 : norm < 3.0 ? 2.0 : norm < 7.0 ? 5.0 : 10.0;
451 return nice * mag;
452 }
453
454 /// Axis label; large scales are abbreviated (500k, 6M).
455 static void label(char* buf, size_t len, double v, double step, int decimals) {
456 if (fabs(v) < step * 1e-6) {
457 snprintf(buf, len, "0");
458 } else if (step >= 1e6) {
459 snprintf(buf, len, "%gM", v / 1e6);
460 } else if (step >= 1e3) {
461 snprintf(buf, len, "%gk", v / 1e3);
462 } else {
463 snprintf(buf, len, "%.*f", decimals, v);
464 }
465 }
466};
467
471
472} // namespace tinymd
Line chart with one or more series, a vertical value scale with round-numbered grid lines,...
Definition: LineChart.h:66
void addValue(int index, float value, size_t maxPoints=0)
Definition: LineChart.h:108
LineChart(Bounds bounds, const char *title=nullptr)
Definition: LineChart.h:69
void clearXAxis()
Removes the X axis labels.
Definition: LineChart.h:163
LineChart()=default
void clearYRange()
Goes back to an automatic Y range.
Definition: LineChart.h:132
void setValues(int index, const std::vector< float > &values)
Replaces the values of the series index.
Definition: LineChart.h:101
bool card
Definition: LineChart.h:76
ChartSeries< RGB_T > & series(int index)
Definition: LineChart.h:98
void setGridValues(const std::vector< float > &values)
Uses exactly these grid values (labelled) instead of the automatic ones.
Definition: LineChart.h:137
int addReferenceLine(float value, RGB_T color, bool dashed=true)
Adds a horizontal reference line and returns its index.
Definition: LineChart.h:115
void setFooter(const char *footer)
One line of text below the plot, e.g. a summary of the values.
Definition: LineChart.h:80
void setSeriesLabel(int index, const char *label)
Definition: LineChart.h:95
void draw(tinygpu::ISurface< RGB_T > &target) override
Definition: LineChart.h:165
void setXAxis(float first, float last, int ticks=3, AxisFormatter format=nullptr)
Definition: LineChart.h:155
void setSeriesDashed(int index, bool dashed)
Draw the series dashed.
Definition: LineChart.h:97
void setValues(int index, const float *values, size_t count)
Definition: LineChart.h:102
void setTitle(const char *title)
Definition: LineChart.h:78
int seriesCount() const
Definition: LineChart.h:91
void setVisiblePoints(int count)
Definition: LineChart.h:141
void setGridCount(int count)
Approximate number of grid lines of the automatic scale (default 4).
Definition: LineChart.h:135
int addSeries(RGB_T color, uint8_t width=2)
Adds a series and returns its index.
Definition: LineChart.h:83
void setReferenceLine(int index, float value)
Definition: LineChart.h:123
void setYRange(float minValue, float maxValue)
Fixes the value range of the Y axis.
Definition: LineChart.h:126
Base class every TinyMaterialDesign widget derives from.
Definition: Widget.h:58
Definition: AnchorLayout.h:4
Axis-aligned pixel rectangle used for widget bounds and hit-testing.
Definition: Bounds.h:21
int32_t right() const
Definition: Bounds.h:30
int32_t bottom() const
Definition: Bounds.h:31
int32_t y
Definition: Bounds.h:23
int32_t x
Definition: Bounds.h:22
A horizontal line at a fixed value, e.g. a threshold or a target.
Definition: LineChart.h:34
float value
Definition: LineChart.h:35
bool dashed
Definition: LineChart.h:37
RGB_T color
Definition: LineChart.h:36
One data series of a LineChart.
Definition: LineChart.h:19
uint8_t width
Line width in pixels.
Definition: LineChart.h:24
std::string label
Name in the legend; series without a label are not listed.
Definition: LineChart.h:29
bool dashed
Draw the line dashed (e.g. to tell apart series of similar colors).
Definition: LineChart.h:27
RGB_T color
Definition: LineChart.h:22
std::vector< float > values
The values, oldest/leftmost first. NaN values break the line.
Definition: LineChart.h:21
bool visible
Definition: LineChart.h:25
Bundles a color scheme, shape tokens, typography, and spacing into one theme, passed to widgets so th...
Definition: MaterialTheme.h:50