D3多折线图的X轴值显示不正确

时间:2018-11-23 11:56:00

标签: javascript d3.js linechart xscale

我已经在我的应用程序中实现了D3v3多折线图。由于我是D3图表的新手,因此寻找了一些在线资源,并提出了这个建议。最初,我必须在X轴上显示Years,并且它工作正常。该小提琴将其显示(https://jsfiddle.net/yasirunilan/tz57wc29/13/)。然后根据一个新的要求,我需要在X轴上显示月份的数据分布,不同之处在于X轴并不总是从一月份开始。如数据集所述,它可能从一年的10月开始到一年的10月到次年的9月开始。在这种情况下,我在图表中显示折线和X轴值时遇到了问题。有人可以为这个问题提供指导吗?

提琴:https://jsfiddle.net/yasirunilan/v160sr4z/10/

    var data = [{
    name: "USA",
    values: [{
        date: "October",
        price: "100"
      },
      {
        date: "November",
        price: "110"
      },
      {
        date: "December",
        price: "145"
      },
      {
        date: "January",
        price: "241"
      },
      {
        date: "February",
        price: "101"
      },
      {
        date: "March",
        price: "90"
      },
      {
        date: "April",
        price: "120"
      },
      {
        date: "May",
        price: "135"
      },
      {
        date: "June",
        price: "99"
      },
      {
        date: "July",
        price: "105"
      },
      {
        date: "August",
        price: "101"
      },
      {
        date: "September",
        price: "106"
      }
    ]
  },
  {
    name: "UK",
    values: [{
        date: "October",
        price: "130"
      },
      {
        date: "November",
        price: "120"
      },
      {
        date: "December",
        price: "115"
      },
      {
        date: "January",
        price: "220"
      },
      {
        date: "February",
        price: "100"
      },
      {
        date: "March",
        price: "140"
      },
      {
        date: "April",
        price: "90"
      },
      {
        date: "May",
        price: "235"
      },
      {
        date: "June",
        price: "160"
      },
      {
        date: "July",
        price: "86"
      },
      {
        date: "August",
        price: "201"
      },
      {
        date: "September",
        price: "140"
      }
    ]
  }
];

const margin = 80;
const width = 1000 - 2 * margin;
const height = 550 - 2 * margin;

var duration = 250;

var lineOpacity = "0.25";
var lineOpacityHover = "0.85";
var otherLinesOpacityHover = "0.1";
var lineStroke = "1.5px";
var lineStrokeHover = "2.5px";

var circleOpacity = '0.85';
var circleOpacityOnLineHover = "0.25"
var circleRadius = 3;
var circleRadiusHover = 6;


/* Format Data */
var parseDate = d3.time.format("%B");
data.forEach(function(d) {
  d.values.forEach(function(d) {
    d.date = parseDate.parse(d.date);
    d.price = +d.price;
  });
});

/* Scale */
var xScale = d3.time.scale()
  .domain(d3.extent(data[0].values, d => d.date))
  .range([0, width - margin]);
var yScale = d3.scale.linear()
  .domain([0, d3.max(data[0].values, d => d.price)])
  .range([height - margin, 0]);

// var color = d3.scale.ordinal(d3.schemeCategory10);
var color = d3.scale.category10();

/* Add SVG */
var svg = d3.select("svg")
  .attr("width", (width + margin) + "px")
  .attr("height", (height + margin) + "px")
  .append('g')
  .attr("transform", `translate(${margin}, ${margin})`);


/* Add line into SVG */
var line = d3.svg.line()
  .x(d => xScale(d.date))
  .y(d => yScale(d.price));

let lines = svg.append('g')
  .attr('class', 'lines');

lines.selectAll('.line-group')
  .data(data).enter()
  .append('g')
  .attr('class', 'line-group')
  .on("mouseover", function(d, i) {
    svg.append("text")
      .attr("class", "title-text")
      .style("fill", color(i))
      .text(d.name)
      .attr("text-anchor", "middle")
      .attr("x", (width - margin) / 2)
      .attr("y", 5);
  })
  .on("mouseout", function(d) {
    svg.select(".title-text").remove();
  })
  .append('path')
  .attr('class', 'line')
  .attr('d', d => line(d.values))
  .style('stroke', (d, i) => color(i))
  .style('opacity', lineOpacity)
  .on("mouseover", function(d) {
    d3.selectAll('.line')
      .style('opacity', otherLinesOpacityHover);
    d3.selectAll('.circle')
      .style('opacity', circleOpacityOnLineHover);
    d3.select(this)
      .style('opacity', lineOpacityHover)
      .style("stroke-width", lineStrokeHover)
      .style("cursor", "pointer");
  })
  .on("mouseout", function(d) {
    d3.selectAll(".line")
      .style('opacity', lineOpacity);
    d3.selectAll('.circle')
      .style('opacity', circleOpacity);
    d3.select(this)
      .style("stroke-width", lineStroke)
      .style("cursor", "none");
  });


/* Add circles in the line */
lines.selectAll("circle-group")
  .data(data).enter()
  .append("g")
  .style("fill", (d, i) => color(i))
  .selectAll("circle")
  .data(d => d.values).enter()
  .append("g")
  .attr("class", "circle")
  .on("mouseover", function(d) {
    d3.select(this)
      .style("cursor", "pointer")
      .append("text")
      .attr("class", "text")
      .text(`${d.price}`)
      .attr("x", d => xScale(d.date) + 5)
      .attr("y", d => yScale(d.price) - 10);
  })
  .on("mouseout", function(d) {
    d3.select(this)
      .style("cursor", "none")
      .transition()
      .duration(duration)
      .selectAll(".text").remove();
  })
  .append("circle")
  .attr("cx", d => xScale(d.date))
  .attr("cy", d => yScale(d.price))
  .attr("r", circleRadius)
  .style('opacity', circleOpacity)
  .on("mouseover", function(d) {
    d3.select(this)
      .transition()
      .duration(duration)
      .attr("r", circleRadiusHover);
  })
  .on("mouseout", function(d) {
    d3.select(this)
      .transition()
      .duration(duration)
      .attr("r", circleRadius);
  });



var xAxis = d3.svg.axis().scale(xScale)
  .orient("bottom").tickFormat(d3.time.format("%B")).tickSize(1);

var yAxis = d3.svg.axis().scale(yScale)
  .orient("left").tickSize(1);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", `translate(0, ${height-margin})`)
  .call(xAxis.ticks(d3.time.year));

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append('text')
  .attr("y", 15)
  .attr("transform", "rotate(-90)")
  .attr("fill", "#000")
  .attr('text-anchor', 'middle')
  .text("No. of Employees");

1 个答案:

答案 0 :(得分:2)

一种可能的解决方案是像这样在date字段中添加年份

{
    date: "2010-October",
    price: "100"
}

如果您不想显示年份,则可以是任意的,只需确保在12月之后将其增加1。

然后将var parseDate = d3.time.format("%B");替换为var parseDate = d3.time.format("%Y-%B");

也将.call(xAxis.ticks(d3.time.year));替换为.call(xAxis.ticks(d3.time.months));

这是小提琴:https://jsfiddle.net/p68z0bqo/


编辑:如果您不能手动添加年份,则可以尝试自动执行以下操作:

var parseDate = d3.time.format("%Y-%B");
data.forEach(function(d) {
  var year = 2000;
  d.values.forEach(function(d) {
    if (d.date === 'January') year++;
    d.date = parseDate.parse(year.toString() + '-' + d.date);
    d.price = +d.price;
  });
});

仅当所有月份都存在(没有间隔)并且一月的确切表示为"January"(即大小写相同)时,此代码才有效。