|
1 | | -import { type ChartConfiguration } from "chart.js"; |
| 1 | +import { type ChartConfiguration, type Plugin } from "chart.js"; |
2 | 2 |
|
3 | 3 | type Vertex = { |
4 | 4 | x: number; |
5 | 5 | y: number; |
6 | 6 | }; |
| 7 | + |
7 | 8 | export function setupPlot(values: number[]): ChartConfiguration { |
8 | | - const rawData: Vertex[] = []; |
9 | | - console.log(values); |
| 9 | + const dataPoints: Vertex[] = []; |
| 10 | + |
| 11 | + const xValues = [] |
| 12 | + const yValues = [] |
| 13 | + |
10 | 14 | for (let i = 0; i < values.length; i += 2) { |
11 | | - rawData.push({ |
12 | | - x: values[i], |
13 | | - y: values[i + 1], |
| 15 | + const x = values[i]; |
| 16 | + const y = values[i + 1]; |
| 17 | + xValues.push(x) |
| 18 | + yValues.push(y) |
| 19 | + dataPoints.push({ |
| 20 | + x, |
| 21 | + y, |
14 | 22 | }); |
15 | 23 | } |
| 24 | + |
| 25 | + xValues.sort() |
| 26 | + yValues.sort() |
| 27 | + const xRange = xValues[xValues.length - 1] - xValues[0] |
| 28 | + const yRange = yValues[yValues.length - 1] - yValues[0] |
| 29 | + const marginRatio = 0.1 |
| 30 | + const xAxisMax = xValues[xValues.length - 1] + xRange * marginRatio |
| 31 | + const xAxisMin = xValues[0] - xRange * marginRatio |
| 32 | + const yAxisMax = yValues[yValues.length - 1] + yRange * marginRatio |
| 33 | + const yAxisMin = yValues[0] - yRange * marginRatio |
16 | 34 | const data = { |
17 | 35 | datasets: [ |
18 | 36 | { |
19 | 37 | label: "Scatter Dataset", |
20 | | - data: rawData, |
| 38 | + data: dataPoints, |
21 | 39 | backgroundColor: "white", |
22 | 40 | borderColor: "black", |
23 | 41 | }, |
24 | 42 | ], |
25 | 43 | }; |
26 | 44 |
|
| 45 | + const plugin: Plugin = { |
| 46 | + id: 'customCanvasBackgroundColor', |
| 47 | + beforeDraw: (chart, args, options) => { |
| 48 | + const {ctx} = chart; |
| 49 | + ctx.save(); |
| 50 | + ctx.globalCompositeOperation = 'destination-over'; |
| 51 | + ctx.fillStyle = options.color || '#FFFFFF'; |
| 52 | + ctx.fillRect(0, 0, chart.width, chart.height); |
| 53 | + ctx.restore(); |
| 54 | + } |
| 55 | +}; |
27 | 56 | const config: ChartConfiguration = { |
28 | 57 | type: "scatter", |
29 | 58 | data: data, |
| 59 | + plugins: [plugin], |
30 | 60 | options: { |
31 | 61 | scales: { |
32 | 62 | x: { |
33 | | - type: "linear", |
34 | | - position: "bottom", |
| 63 | + max: xAxisMax, |
| 64 | + min: xAxisMin |
35 | 65 | }, |
| 66 | + y: { |
| 67 | + max: yAxisMax, |
| 68 | + min: yAxisMin |
| 69 | + } |
36 | 70 | }, |
37 | 71 | }, |
38 | 72 | }; |
|
0 commit comments