scatter.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. import uPlot from 'uplot';
  2. import {
  3. DataFrame,
  4. FieldColorModeId,
  5. fieldColorModeRegistry,
  6. getDisplayProcessor,
  7. getFieldColorModeForField,
  8. getFieldDisplayName,
  9. getFieldSeriesColor,
  10. GrafanaTheme2,
  11. } from '@grafana/data';
  12. import { alpha } from '@grafana/data/src/themes/colorManipulator';
  13. import { config } from '@grafana/runtime';
  14. import { AxisPlacement, ScaleDirection, ScaleOrientation, VisibilityMode } from '@grafana/schema';
  15. import { UPlotConfigBuilder } from '@grafana/ui';
  16. import { FacetedData, FacetSeries } from '@grafana/ui/src/components/uPlot/types';
  17. import {
  18. findFieldIndex,
  19. getScaledDimensionForField,
  20. ScaleDimensionConfig,
  21. ScaleDimensionMode,
  22. } from 'app/features/dimensions';
  23. import { pointWithin, Quadtree, Rect } from '../barchart/quadtree';
  24. import { isGraphable } from './dims';
  25. import { defaultScatterConfig, ScatterFieldConfig, ScatterLineMode, XYChartOptions } from './models.gen';
  26. import { DimensionValues, ScatterHoverCallback, ScatterSeries } from './types';
  27. export interface ScatterPanelInfo {
  28. error?: string;
  29. series: ScatterSeries[];
  30. builder?: UPlotConfigBuilder;
  31. }
  32. /**
  33. * This is called when options or structure rev changes
  34. */
  35. export function prepScatter(
  36. options: XYChartOptions,
  37. getData: () => DataFrame[],
  38. theme: GrafanaTheme2,
  39. ttip: ScatterHoverCallback
  40. ): ScatterPanelInfo {
  41. let series: ScatterSeries[];
  42. let builder: UPlotConfigBuilder;
  43. try {
  44. series = prepSeries(options, getData());
  45. builder = prepConfig(getData, series, theme, ttip);
  46. } catch (e) {
  47. console.log('prepScatter ERROR', e);
  48. return {
  49. error: e.message,
  50. series: [],
  51. };
  52. }
  53. return {
  54. series,
  55. builder,
  56. };
  57. }
  58. interface Dims {
  59. pointColorIndex?: number;
  60. pointColorFixed?: string;
  61. pointSizeIndex?: number;
  62. pointSizeConfig?: ScaleDimensionConfig;
  63. }
  64. function getScatterSeries(
  65. seriesIndex: number,
  66. frames: DataFrame[],
  67. frameIndex: number,
  68. xIndex: number,
  69. yIndex: number,
  70. dims: Dims
  71. ): ScatterSeries {
  72. const frame = frames[frameIndex];
  73. const y = frame.fields[yIndex];
  74. let state = y.state ?? {};
  75. state.seriesIndex = seriesIndex;
  76. y.state = state;
  77. // Color configs
  78. //----------------
  79. let seriesColor = dims.pointColorFixed
  80. ? config.theme2.visualization.getColorByName(dims.pointColorFixed)
  81. : getFieldSeriesColor(y, config.theme2).color;
  82. let pointColor: DimensionValues<string> = () => seriesColor;
  83. const fieldConfig: ScatterFieldConfig = { ...defaultScatterConfig, ...y.config.custom };
  84. let pointColorMode = fieldColorModeRegistry.get(FieldColorModeId.PaletteClassic);
  85. if (dims.pointColorIndex) {
  86. const f = frames[frameIndex].fields[dims.pointColorIndex];
  87. if (f) {
  88. const disp =
  89. f.display ??
  90. getDisplayProcessor({
  91. field: f,
  92. theme: config.theme2,
  93. });
  94. pointColorMode = getFieldColorModeForField(y);
  95. if (pointColorMode.isByValue) {
  96. const index = dims.pointColorIndex;
  97. pointColor = (frame: DataFrame) => {
  98. // Yes we can improve this later
  99. return frame.fields[index].values.toArray().map((v) => disp(v).color!);
  100. };
  101. } else {
  102. seriesColor = pointColorMode.getCalculator(f, config.theme2)(f.values.get(0), 1);
  103. pointColor = () => seriesColor;
  104. }
  105. }
  106. }
  107. // Size configs
  108. //----------------
  109. let pointSizeHints = dims.pointSizeConfig;
  110. let pointSizeFixed = dims.pointSizeConfig?.fixed ?? y.config.custom?.pointSizeConfig?.fixed ?? 5;
  111. let pointSize: DimensionValues<number> = () => pointSizeFixed;
  112. if (dims.pointSizeIndex) {
  113. pointSize = (frame) => {
  114. const s = getScaledDimensionForField(
  115. frame.fields[dims.pointSizeIndex!],
  116. dims.pointSizeConfig!,
  117. ScaleDimensionMode.Quadratic
  118. );
  119. const vals = Array(frame.length);
  120. for (let i = 0; i < frame.length; i++) {
  121. vals[i] = s.get(i);
  122. }
  123. return vals;
  124. };
  125. } else {
  126. pointSizeHints = {
  127. fixed: pointSizeFixed,
  128. min: pointSizeFixed,
  129. max: pointSizeFixed,
  130. };
  131. }
  132. // Series config
  133. //----------------
  134. const name = getFieldDisplayName(y, frame, frames);
  135. return {
  136. name,
  137. frame: (frames) => frames[frameIndex],
  138. x: (frame) => frame.fields[xIndex],
  139. y: (frame) => frame.fields[yIndex],
  140. legend: (frame) => {
  141. return [
  142. {
  143. label: name,
  144. color: seriesColor, // single color for series?
  145. getItemKey: () => name,
  146. yAxis: yIndex, // << but not used
  147. },
  148. ];
  149. },
  150. line: fieldConfig.line ?? ScatterLineMode.None,
  151. lineWidth: fieldConfig.lineWidth ?? 2,
  152. lineStyle: fieldConfig.lineStyle!,
  153. lineColor: () => seriesColor,
  154. point: fieldConfig.point!,
  155. pointSize,
  156. pointColor,
  157. pointSymbol: (frame: DataFrame, from?: number) => 'circle', // single field, multiple symbols.... kinda equals multiple series 🤔
  158. label: VisibilityMode.Never,
  159. labelValue: () => '',
  160. hints: {
  161. pointSize: pointSizeHints!,
  162. pointColor: {
  163. mode: pointColorMode,
  164. },
  165. },
  166. };
  167. }
  168. function prepSeries(options: XYChartOptions, frames: DataFrame[]): ScatterSeries[] {
  169. let seriesIndex = 0;
  170. if (!frames.length) {
  171. throw 'missing data';
  172. }
  173. if (options.mode === 'explicit') {
  174. if (options.series?.length) {
  175. for (const series of options.series) {
  176. if (!series?.x) {
  177. throw 'Select X dimension';
  178. }
  179. if (!series?.y) {
  180. throw 'Select Y dimension';
  181. }
  182. for (let frameIndex = 0; frameIndex < frames.length; frameIndex++) {
  183. const frame = frames[frameIndex];
  184. const xIndex = findFieldIndex(frame, series.x);
  185. if (xIndex != null) {
  186. // TODO: this should find multiple y fields
  187. const yIndex = findFieldIndex(frame, series.y);
  188. if (yIndex == null) {
  189. throw 'Y must be in the same frame as X';
  190. }
  191. const dims: Dims = {
  192. pointColorFixed: series.pointColor?.fixed,
  193. pointColorIndex: findFieldIndex(frame, series.pointColor?.field),
  194. pointSizeConfig: series.pointSize,
  195. pointSizeIndex: findFieldIndex(frame, series.pointSize?.field),
  196. };
  197. return [getScatterSeries(seriesIndex++, frames, frameIndex, xIndex, yIndex, dims)];
  198. }
  199. }
  200. }
  201. }
  202. }
  203. // Default behavior
  204. const dims = options.dims ?? {};
  205. const frameIndex = dims.frame ?? 0;
  206. const frame = frames[frameIndex];
  207. const numericIndicies: number[] = [];
  208. let xIndex = findFieldIndex(frame, dims.x);
  209. for (let i = 0; i < frame.fields.length; i++) {
  210. if (isGraphable(frame.fields[i])) {
  211. if (xIndex == null || i === xIndex) {
  212. xIndex = i;
  213. continue;
  214. }
  215. if (dims.exclude && dims.exclude.includes(getFieldDisplayName(frame.fields[i], frame, frames))) {
  216. continue; // skip
  217. }
  218. numericIndicies.push(i);
  219. }
  220. }
  221. if (xIndex == null) {
  222. throw 'Missing X dimension';
  223. }
  224. if (!numericIndicies.length) {
  225. throw 'No Y values';
  226. }
  227. return numericIndicies.map((yIndex) => getScatterSeries(seriesIndex++, frames, frameIndex, xIndex!, yIndex, {}));
  228. }
  229. interface DrawBubblesOpts {
  230. each: (u: uPlot, seriesIdx: number, dataIdx: number, lft: number, top: number, wid: number, hgt: number) => void;
  231. disp: {
  232. //unit: 3,
  233. size: {
  234. values: (u: uPlot, seriesIdx: number) => number[];
  235. };
  236. color: {
  237. values: (u: uPlot, seriesIdx: number) => string[];
  238. alpha: (u: uPlot, seriesIdx: number) => string[];
  239. };
  240. };
  241. }
  242. //const prepConfig: UPlotConfigPrepFnXY<XYChartOptions> = ({ frames, series, theme }) => {
  243. const prepConfig = (
  244. getData: () => DataFrame[],
  245. scatterSeries: ScatterSeries[],
  246. theme: GrafanaTheme2,
  247. ttip: ScatterHoverCallback
  248. ) => {
  249. let qt: Quadtree;
  250. let hRect: Rect | null;
  251. function drawBubblesFactory(opts: DrawBubblesOpts) {
  252. const drawBubbles: uPlot.Series.PathBuilder = (u, seriesIdx, idx0, idx1) => {
  253. uPlot.orient(
  254. u,
  255. seriesIdx,
  256. (
  257. series,
  258. dataX,
  259. dataY,
  260. scaleX,
  261. scaleY,
  262. valToPosX,
  263. valToPosY,
  264. xOff,
  265. yOff,
  266. xDim,
  267. yDim,
  268. moveTo,
  269. lineTo,
  270. rect,
  271. arc
  272. ) => {
  273. const scatterInfo = scatterSeries[seriesIdx - 1];
  274. let d = u.data[seriesIdx] as unknown as FacetSeries;
  275. let showLine = scatterInfo.line !== ScatterLineMode.None;
  276. let showPoints = scatterInfo.point === VisibilityMode.Always;
  277. if (!showPoints && scatterInfo.point === VisibilityMode.Auto) {
  278. showPoints = d[0].length < 1000;
  279. }
  280. // always show something
  281. if (!showPoints && !showLine) {
  282. showLine = true;
  283. }
  284. let strokeWidth = 1;
  285. u.ctx.save();
  286. u.ctx.rect(u.bbox.left, u.bbox.top, u.bbox.width, u.bbox.height);
  287. u.ctx.clip();
  288. u.ctx.fillStyle = (series.fill as any)(); // assumes constant
  289. u.ctx.strokeStyle = (series.stroke as any)();
  290. u.ctx.lineWidth = strokeWidth;
  291. let deg360 = 2 * Math.PI;
  292. let xKey = scaleX.key!;
  293. let yKey = scaleY.key!;
  294. let pointHints = scatterInfo.hints.pointSize;
  295. const colorByValue = scatterInfo.hints.pointColor.mode.isByValue;
  296. let maxSize = (pointHints.max ?? pointHints.fixed) * devicePixelRatio;
  297. // todo: this depends on direction & orientation
  298. // todo: calc once per redraw, not per path
  299. let filtLft = u.posToVal(-maxSize / 2, xKey);
  300. let filtRgt = u.posToVal(u.bbox.width / devicePixelRatio + maxSize / 2, xKey);
  301. let filtBtm = u.posToVal(u.bbox.height / devicePixelRatio + maxSize / 2, yKey);
  302. let filtTop = u.posToVal(-maxSize / 2, yKey);
  303. let sizes = opts.disp.size.values(u, seriesIdx);
  304. let pointColors = opts.disp.color.values(u, seriesIdx);
  305. let pointAlpha = opts.disp.color.alpha(u, seriesIdx);
  306. let linePath: Path2D | null = showLine ? new Path2D() : null;
  307. for (let i = 0; i < d[0].length; i++) {
  308. let xVal = d[0][i];
  309. let yVal = d[1][i];
  310. let size = sizes[i] * devicePixelRatio;
  311. if (xVal >= filtLft && xVal <= filtRgt && yVal >= filtBtm && yVal <= filtTop) {
  312. let cx = valToPosX(xVal, scaleX, xDim, xOff);
  313. let cy = valToPosY(yVal, scaleY, yDim, yOff);
  314. if (showLine) {
  315. linePath!.lineTo(cx, cy);
  316. }
  317. if (showPoints) {
  318. u.ctx.moveTo(cx + size / 2, cy);
  319. u.ctx.beginPath();
  320. u.ctx.arc(cx, cy, size / 2, 0, deg360);
  321. if (colorByValue) {
  322. u.ctx.fillStyle = pointAlpha[i];
  323. u.ctx.strokeStyle = pointColors[i];
  324. }
  325. u.ctx.fill();
  326. u.ctx.stroke();
  327. opts.each(
  328. u,
  329. seriesIdx,
  330. i,
  331. cx - size / 2 - strokeWidth / 2,
  332. cy - size / 2 - strokeWidth / 2,
  333. size + strokeWidth,
  334. size + strokeWidth
  335. );
  336. }
  337. }
  338. }
  339. if (showLine) {
  340. let frame = scatterInfo.frame(getData());
  341. u.ctx.strokeStyle = scatterInfo.lineColor(frame);
  342. u.ctx.lineWidth = scatterInfo.lineWidth * devicePixelRatio;
  343. const { lineStyle } = scatterInfo;
  344. if (lineStyle && lineStyle.fill !== 'solid') {
  345. if (lineStyle.fill === 'dot') {
  346. u.ctx.lineCap = 'round';
  347. }
  348. u.ctx.setLineDash(lineStyle.dash ?? [10, 10]);
  349. }
  350. u.ctx.stroke(linePath!);
  351. }
  352. u.ctx.restore();
  353. }
  354. );
  355. return null;
  356. };
  357. return drawBubbles;
  358. }
  359. let drawBubbles = drawBubblesFactory({
  360. disp: {
  361. size: {
  362. //unit: 3, // raw CSS pixels
  363. values: (u, seriesIdx) => {
  364. return u.data[seriesIdx][2] as any; // already contains final pixel geometry
  365. //let [minValue, maxValue] = getSizeMinMax(u);
  366. //return u.data[seriesIdx][2].map(v => getSize(v, minValue, maxValue));
  367. },
  368. },
  369. color: {
  370. // string values
  371. values: (u, seriesIdx) => {
  372. return u.data[seriesIdx][3] as any;
  373. },
  374. alpha: (u, seriesIdx) => {
  375. return u.data[seriesIdx][4] as any;
  376. },
  377. },
  378. },
  379. each: (u, seriesIdx, dataIdx, lft, top, wid, hgt) => {
  380. // we get back raw canvas coords (included axes & padding). translate to the plotting area origin
  381. lft -= u.bbox.left;
  382. top -= u.bbox.top;
  383. qt.add({ x: lft, y: top, w: wid, h: hgt, sidx: seriesIdx, didx: dataIdx });
  384. },
  385. });
  386. const builder = new UPlotConfigBuilder();
  387. builder.setCursor({
  388. drag: { setScale: true },
  389. dataIdx: (u, seriesIdx) => {
  390. if (seriesIdx === 1) {
  391. hRect = null;
  392. let dist = Infinity;
  393. let cx = u.cursor.left! * devicePixelRatio;
  394. let cy = u.cursor.top! * devicePixelRatio;
  395. qt.get(cx, cy, 1, 1, (o) => {
  396. if (pointWithin(cx, cy, o.x, o.y, o.x + o.w, o.y + o.h)) {
  397. let ocx = o.x + o.w / 2;
  398. let ocy = o.y + o.h / 2;
  399. let dx = ocx - cx;
  400. let dy = ocy - cy;
  401. let d = Math.sqrt(dx ** 2 + dy ** 2);
  402. // test against radius for actual hover
  403. if (d <= o.w / 2) {
  404. // only hover bbox with closest distance
  405. if (d <= dist) {
  406. dist = d;
  407. hRect = o;
  408. }
  409. }
  410. }
  411. });
  412. }
  413. return hRect && seriesIdx === hRect.sidx ? hRect.didx : null;
  414. },
  415. points: {
  416. size: (u, seriesIdx) => {
  417. return hRect && seriesIdx === hRect.sidx ? hRect.w / devicePixelRatio : 0;
  418. },
  419. fill: (u, seriesIdx) => 'rgba(255,255,255,0.4)',
  420. },
  421. });
  422. // clip hover points/bubbles to plotting area
  423. builder.addHook('init', (u, r) => {
  424. u.over.style.overflow = 'hidden';
  425. });
  426. let rect: DOMRect;
  427. // rect of .u-over (grid area)
  428. builder.addHook('syncRect', (u, r) => {
  429. rect = r;
  430. });
  431. builder.addHook('setLegend', (u) => {
  432. // console.log('TTIP???', u.cursor.idxs);
  433. if (u.cursor.idxs != null) {
  434. for (let i = 0; i < u.cursor.idxs.length; i++) {
  435. const sel = u.cursor.idxs[i];
  436. if (sel != null) {
  437. ttip({
  438. scatterIndex: i - 1,
  439. xIndex: sel,
  440. pageX: rect.left + u.cursor.left!,
  441. pageY: rect.top + u.cursor.top!,
  442. });
  443. return; // only show the first one
  444. }
  445. }
  446. }
  447. ttip(undefined);
  448. });
  449. builder.addHook('drawClear', (u) => {
  450. qt = qt || new Quadtree(0, 0, u.bbox.width, u.bbox.height);
  451. qt.clear();
  452. // force-clear the path cache to cause drawBars() to rebuild new quadtree
  453. u.series.forEach((s, i) => {
  454. if (i > 0) {
  455. // @ts-ignore
  456. s._paths = null;
  457. }
  458. });
  459. });
  460. builder.setMode(2);
  461. const frames = getData();
  462. let xField = scatterSeries[0].x(scatterSeries[0].frame(frames));
  463. builder.addScale({
  464. scaleKey: 'x',
  465. isTime: false,
  466. orientation: ScaleOrientation.Horizontal,
  467. direction: ScaleDirection.Right,
  468. range: (u, min, max) => [min, max],
  469. });
  470. builder.addAxis({
  471. scaleKey: 'x',
  472. placement:
  473. xField.config.custom?.axisPlacement !== AxisPlacement.Hidden ? AxisPlacement.Bottom : AxisPlacement.Hidden,
  474. show: xField.config.custom?.axisPlacement !== AxisPlacement.Hidden,
  475. theme,
  476. label: xField.config.custom.axisLabel,
  477. });
  478. scatterSeries.forEach((s) => {
  479. let frame = s.frame(frames);
  480. let field = s.y(frame);
  481. const lineColor = s.lineColor(frame);
  482. const pointColor = asSingleValue(frame, s.pointColor) as string;
  483. //const lineColor = s.lineColor(frame);
  484. //const lineWidth = s.lineWidth;
  485. let scaleKey = field.config.unit ?? 'y';
  486. builder.addScale({
  487. scaleKey,
  488. orientation: ScaleOrientation.Vertical,
  489. direction: ScaleDirection.Up,
  490. range: (u, min, max) => [min, max],
  491. });
  492. if (field.config.custom?.axisPlacement !== AxisPlacement.Hidden) {
  493. builder.addAxis({
  494. scaleKey,
  495. theme,
  496. placement: field.config.custom?.axisPlacement,
  497. label: field.config.custom.axisLabel,
  498. values: (u, splits) => splits.map((s) => field.display!(s).text),
  499. });
  500. }
  501. builder.addSeries({
  502. facets: [
  503. {
  504. scale: 'x',
  505. auto: true,
  506. },
  507. {
  508. scale: scaleKey,
  509. auto: true,
  510. },
  511. ],
  512. pathBuilder: drawBubbles, // drawBubbles({disp: {size: {values: () => }}})
  513. theme,
  514. scaleKey: '', // facets' scales used (above)
  515. lineColor: lineColor as string,
  516. fillColor: alpha(pointColor, 0.5),
  517. });
  518. });
  519. /*
  520. builder.setPrepData((frames) => {
  521. let seriesData = lookup.fieldMaps.flatMap((f, i) => {
  522. let { fields } = frames[i];
  523. return f.y.map((yIndex, frameSeriesIndex) => {
  524. let xValues = fields[f.x[frameSeriesIndex]].values.toArray();
  525. let yValues = fields[f.y[frameSeriesIndex]].values.toArray();
  526. let sizeValues = f.size![frameSeriesIndex](frames[i]);
  527. if (!Array.isArray(sizeValues)) {
  528. sizeValues = Array(xValues.length).fill(sizeValues);
  529. }
  530. return [xValues, yValues, sizeValues];
  531. });
  532. });
  533. return [null, ...seriesData];
  534. });
  535. */
  536. return builder;
  537. };
  538. /**
  539. * This is called everytime the data changes
  540. *
  541. * from? is this where we would support that? -- need the previous values
  542. */
  543. export function prepData(info: ScatterPanelInfo, data: DataFrame[], from?: number): FacetedData {
  544. if (info.error) {
  545. return [null];
  546. }
  547. return [
  548. null,
  549. ...info.series.map((s, idx) => {
  550. const frame = s.frame(data);
  551. let colorValues;
  552. let colorAlphaValues;
  553. const r = s.pointColor(frame);
  554. if (Array.isArray(r)) {
  555. colorValues = r;
  556. colorAlphaValues = r.map((c) => alpha(c as string, 0.5));
  557. } else {
  558. colorValues = Array(frame.length).fill(r);
  559. colorAlphaValues = Array(frame.length).fill(alpha(r as string, 0.5));
  560. }
  561. return [
  562. s.x(frame).values.toArray(), // X
  563. s.y(frame).values.toArray(), // Y
  564. asArray(frame, s.pointSize),
  565. colorValues,
  566. colorAlphaValues,
  567. ];
  568. }),
  569. ];
  570. }
  571. function asArray<T>(frame: DataFrame, lookup: DimensionValues<T>): T[] {
  572. const r = lookup(frame);
  573. if (Array.isArray(r)) {
  574. return r;
  575. }
  576. return Array(frame.length).fill(r);
  577. }
  578. function asSingleValue<T>(frame: DataFrame, lookup: DimensionValues<T>): T {
  579. const r = lookup(frame);
  580. if (Array.isArray(r)) {
  581. return r[0];
  582. }
  583. return r;
  584. }