Как создать многострочный график, вложив данные в D3 - PullRequest
0 голосов
/ 04 октября 2019

Я пытаюсь создать многоуровневый линейный график, и мой график выглядит следующим образом: d3

Я мог бы просто добавить путь для каждой области без вложенностиданные, но это требует многократного кодирования, и я хотел знать, как я могу использовать логику вложения. Я проверил свои данные, и они правильно вложены, но, возможно, я не вижу того, что должен видеть.

Код:

// set the dimensions and margins of the graph
var margin = {top: 30, right: 30, bottom: 30, left: 60},
    width = 1000 - margin.left - margin.right,
    height = 600 - margin.top - margin.bottom;


var get_year = d3.timeParse("%Y");

// read the csv file
d3.csv("state-year-earthquakes.csv").then(data => {
data.forEach(d => {
  d.state = d.state
  d.region = d.region
  d.year = get_year(+d.year)
  d.count = +d.count
});
render(data)
});


const render = data => {

  var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")")
    ;
  // nest the data 
  var sumstat = d3.nest()
    .key(function(d) {return d.region;})
    .entries(data);
console.log(sumstat)
   // Add X axis --> it is a date format
  var x = d3.scaleTime()
    .domain(d3.extent(data, function(d) { return d.year; }))
    .range([ 0, width ]);
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x).ticks(5));

  // Add Y axis
  var y = d3.scaleLinear()
    .domain([0, d3.max(data, function(d) { return +d.count; })])
    .range([ height, 0 ]);
  svg.append("g")
    .call(d3.axisLeft(y));

 // color palette
  var res = sumstat.map(function(d){ return d.key })

   // list of group names
  var color = d3.scaleOrdinal()
    .domain(res)
    .range(['#e41a1c','#4daf4a','#984ea3','#a65628'])

var line = d3.line()
    .x(function(d) { return x(d.year); })
    .y(function(d) { return y(+d.count); });

// Draw the line
  svg.selectAll(".line-path")
      .data(sumstat)
      .enter()
      .append("path")
        .attr("fill", "none")
        .attr("stroke", function(d){ return color(d.key) })
        .attr("stroke-width", 1.5)
        .attr("d", d => line(d.values))

  // text label for the x axis
  svg.append("text")             
      .attr("transform",
            "translate(" + (width/2) + " ," + 
                           (height + margin.top + 20) + ")")
      .style("text-anchor", "middle")
      .attr("font-family", "arial")
      .text("Year");

  // text label for the y axis
  svg.append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 0-margin.left)
      .attr("x",0 - (height / 2))
      .attr("dy", "1em")
      .style("text-anchor", "middle")
      .attr("font-family", "arial")
      .text("Num of Earthquakes"); 

// add a chart title
svg.append("text")
        .attr("x", (width / 2))             
        .attr("y", 0 - (margin.top / 3))
        .attr("text-anchor", "middle")  
        .style("font-size", "18px") 
        .style("text-decoration", "underline")  
        .attr("font-weight","bold")
        .attr("font-family", "arial")
        .text("Worldwide Earthquake stats 2000-2015");

// create a legend
var legend = svg.append("g")
  .attr("class", "legend")
  .attr("x", width)
  .attr("y", 25)
  .attr("height", 100)
  .attr("width", 100)

legend.append("circle")
  .attr("cx", width-110)
  .attr("cy", 29)
  .attr("r", 6)
  .style("fill", '#e41a1c')


legend.append("text")
  .attr("x", width - 100)
  .attr("y", 35)
  .text("Midwest")
  .attr("font-family", "arial"); 

var legend = svg.append("g")
  .attr("class", "legend")
  .attr("x", 600)
  .attr("y", 25)
  .attr("height", 100)
  .attr("width", 100)

legend.append("circle")
  .attr("cx", width - 110 )
  .attr("cy", 46)
  .attr("r", 6)
  .style("fill", '#4daf4a')

legend.append("text")
  .attr("x", width-100)
  .attr("y", 52)
  .text("Northeast")
  .attr("font-family", "arial");  


var legend = svg.append("g")
  .attr("class", "legend")
  .attr("x", 500)
  .attr("y", 25)
  .attr("height", 100)
  .attr("width", 100)

legend.append("circle")
  .attr("cx", width - 110)
  .attr("cy", 63)
  .attr("r", 6)
  .style("fill", '#984ea3')

legend.append("text")
  .attr("x", width - 100)
  .attr("y", 69)
  .text("South")
  .attr("font-family", "arial");  

var legend = svg.append("g")
  .attr("class", "legend")
  .attr("x", 600)
  .attr("y", 25)
  .attr("height", 100)
  .attr("width", 100)

legend.append("circle")
  .attr("cx", width-110)
  .attr("cy",80 )
  .attr("r", 6)
  .style("fill", '#a65628')

legend.append("text")
  .attr("x", width - 100)
  .attr("y", 86)
  .text("West")
  .attr("font-family", "arial");

}
...