Xiao H
Xiao H

Reputation: 165

d3 line chart x, y not in the same level of a data structure, how to set x, y function?

I have seen many examples, it looks like the data to put into (x, y) should be in the same level, like this

date,A,B,C
20-Jul-2019,10,20,16
21-Jul-2019,11,22,18
22-Jul-2019,13,19,21

however in my case my data structure is bit different, my x comes from the first level but my y comes from second level:

const data = [
        {
          name: "A",
          values: [{ source: "series_1", value: 10 }],
        },
        {
          name: "B",
          values: [{ source: "series_1", value: 22 }],
        },]

so it will not work like this:

    let line = d3
        .line()
        .x((d) => xScale(d.name))
        .y((d) => yScale(d.values.value))
        .curve(d3.curveBasis);
      let path = mainGraph
        .selectAll("path")
        .data(data)
        .enter()
        .append("g")
        .attr("class", "path");
      path
        .append("path")
        .attr("class", "line")
        .attr("d", (d) => line(d.values));

I tried several ways but couldn't work out, do I need to adjust my data, so name and value will be in the same level for d3 to draw the line chart? Thank you!

Upvotes: 0

Views: 91

Answers (1)

D.icon
D.icon

Reputation: 396

you should reach the inner value by using: .y((d) => yScale(d.values[0].value)).

Upvotes: 1

Related Questions