【问题标题】:Line Chart path in D3 JS not displaying ProperlyD3 JS中的折线图路径未正确显示
【发布时间】:2021-11-22 20:34:42
【问题描述】:

我正在尝试通过此功能实现折线图。当我尝试添加路径时,没有单独显示路径。任何帮助,将不胜感激。 (代码的最后 10 行添加了图形的路径)

function drawLineChart(country) {
  console.log(countryValueMap[country])
   var margin = {top: 60, right: 110, bottom: 50, left: 50},
    width = 800 - margin.left - margin.right + 50,
    height = 500 - margin.top - margin.bottom + 50;
    // document.getElementById("my_dataviz").innerHTML = "";
    const lineSvg = d3.select("#linechart")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`);

    const x = d3.scaleTime()
  .range([0 , width])
  .domain([new Date(1958,0,1), new Date(2011,0,1)])

lineSvg.append("g")
  .attr("transform", `translate(0, ${height})`)
  .call(d3.axisBottom(x).ticks(5).tickFormat(d => d.getFullYear()))

const y = d3.scaleLinear()
  .domain([0,countryMaxValueMap[country]])
  .range([height, 0])
lineSvg.append("g")
  .call(d3.axisRight(y).tickSize(width)).call(g => g.select(".domain")
        .remove())
    .call(g => g.selectAll(".tick:not(:first-of-type) line")
        .attr("stroke-opacity", 0.5)
        .attr("stroke-dasharray", "2,2"))
    .call(g => g.selectAll(".tick text")
        .attr("x", 4)
        .attr("dy", -4));


    lineSvg.append("path")
      .datum(countryValueMap[country])
      .attr("fill", "none")
      .attr("stroke", "steelblue")
      .attr("stroke-width", 1.5)
      .attr("d", d3.line()
        .x(function(d) { return x(d.year) })
        .y(function(d) { return y(d.gdp) })
        )
}

当我尝试执行上述代码时,这是我得到的输出。

我尝试记录 d3.year 和 d3.gdp 的值,变量工作正常。

【问题讨论】:

  • 你能分享countryValueMap吗?鉴于该行位于 1970 年(纪元时间的开始),您的数据中表示年份的方式似乎有问题。由于您使用的是scaleTime,因此d.year 必须是日期对象。它不能只是代表年份的整数。
  • @Dan 成功了,谢谢,将其作为回复发布。我会将其标记为解决方案

标签: javascript d3.js data-visualization linechart


【解决方案1】:

鉴于该行位于 1970 年(纪元时间的开始),您的数据中的年份表示方式似乎有问题。由于您使用的是scaleTime,因此d.year 必须是一个日期对象。它不能只是代表年份的整数。

【讨论】:

    猜你喜欢
    • 2013-01-09
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多