-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathScatterPlot.tsx
More file actions
97 lines (84 loc) · 2.69 KB
/
ScatterPlot.tsx
File metadata and controls
97 lines (84 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import * as React from "react";
import { useLoaderData } from "react-router";
import * as d3 from "d3";
import Chart from "../components/Chart";
import Axis from "../components/Axis";
import type { weatherDataLoader, WeatherData } from "../loaders";
import type { BoundedDimensions } from "../utils/types";
import styles from "./styles/Scatterplot.module.css";
//* Step 1b. Access Data
const xAccessor = (d: WeatherData) => d.dewPoint;
const yAccessor = (d: WeatherData) => d.humidity;
const colorAccessor = (d: WeatherData) => d.cloudCover;
//* Step 2. Create chart dimensions
const chartSize = d3.min([
window.innerWidth * 0.9,
window.innerHeight * 0.9,
]) as number;
const dimensions: BoundedDimensions = {
width: chartSize,
height: chartSize,
margin: {
top: 10,
right: 10,
bottom: 50,
left: 50,
},
boundedWidth: 0,
boundedHeight: 0,
};
dimensions.boundedWidth =
dimensions.width - dimensions.margin.left - dimensions.margin.right;
dimensions.boundedHeight =
dimensions.height - dimensions.margin.top - dimensions.margin.bottom;
const formatTick = d3.format(".1f");
function ScatterPlot() {
const dataset = useLoaderData<typeof weatherDataLoader>();
//* Step 4. Create scales
const xScale = d3
.scaleTime()
.domain(d3.extent(dataset, xAccessor) as [number, number])
.range([0, dimensions.boundedWidth])
.nice();
const yScale = d3
.scaleLinear()
.domain(d3.extent(dataset, yAccessor) as [number, number])
.range([dimensions.boundedHeight, 0])
.nice();
const colorScale = d3
//? We need string types for the color range values
.scaleLinear<string>()
.domain(d3.extent(dataset, colorAccessor) as [number, number])
.range(["skyblue", "darkslategrey"]);
const xAccessorScaled = (d: WeatherData) => xScale(xAccessor(d));
const yAccessorScaled = (d: WeatherData) => yScale(yAccessor(d));
const colorAccessorScaled = (d: WeatherData) => colorScale(colorAccessor(d));
return (
<div className={styles.wrapper}>
{/* Step 3. Draw canvas */}
<Chart dimensions={dimensions}>
{/* Step 5. Draw data */}
{dataset?.map((data, idx) => (
<circle
key={idx}
cx={xAccessorScaled(data)}
cy={yAccessorScaled(data)}
// fill="cornflowerblue"
fill={colorAccessorScaled(data)}
r={5}
/>
))}
{/* Step 6. Draw peripherals */}
<Axis dimension="x" scale={xScale} label="Dew point (°F)" />
<Axis
dimension="y"
scale={yScale}
numberOfTicks={4}
formatTick={formatTick}
label="Relative Humidity"
/>
</Chart>
</div>
);
}
export default ScatterPlot;