2

I test d3 examples. but i have an error.

enter image description here

ps. I solved this error. but not beautiful.

        const xextent = d3.extent(data, (d) => d.x);
        const x = d3
            .scaleLinear()
            .domain([xextent[0] ?? 0, xextent[1] ?? 0])
            .nice()
            .range([margin.left, width - margin.right]);
  • I found error reason. d3.extent(data,(d)=> d.x) can return [undefined, undefined]. but i can not fix it. – HaJong Jeong Jul 16 '20 at 14:15
  • 1
    On Stackoverflow it is much preferred to copy paste the code and error into code tags than to use screenshots. Images cannot be indexed by search engines and tend to last less on the internet than text. – AnLog Jul 16 '20 at 14:19

2 Answers2

1

you can put in a check between calculating the extent and passing it to the domain function, like this

const domain = d3.extent([1, 2, 3], (d) => d);
if (!domain[0] || !domain[1]) {
  throw new Error("found unexpected value while getting x scale");
}
return d3
  .scaleLinear()
  .domain(domain)
  .range([margins.left, totalWidth - margins.right]);
Joey Gough
  • 2,753
  • 2
  • 21
  • 42
0

You can either set the default when destructuring the array

let [min = 0, max = 140] = d3.extent(data.map((d) => d[0]));
let xScale = d3.scaleLinear().domain([min, max]).range([0, width]);

Or cast it inline if you're sure the data isn't undefined. This is cleaner visually.

let yScale = d3
  .scaleLinear()
  .domain(d3.extent(data.map((d) => d[1])) as [number, number]) // <--
  .range([0, height]);
wongz
  • 3,255
  • 2
  • 28
  • 55