如何在x轴上绘制带有月/年的D3条形图,以天为月间距

时间:2017-10-12 06:02:28

标签: javascript d3.js bar-chart

我试图在x轴上实现带有日期的D3 js条形图,而标签应该只显示月份和天数作为它们之间的间距。 我能够生成图表chart并且代码为code

data = [
  {
    "count": 3,
    "date": "2017-04-01T00:00:00.000Z"
  },
  {
    "count": 3,
    "date": "2017-05-01T00:00:00.000Z"
  },
  {
    "count": 2,
    "date": "2017-06-01T00:00:00.000Z"
  }
];
let margin = {top: 20, right: 20, bottom: 70, left: 40},
  width = 600 - margin.left - margin.right,
  height = 200 - margin.top - margin.bottom;

  let x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
  let y = d3.scale.linear().range([height, 0]);

  let xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom")
      .tickFormat(d3.time.format("%m/%Y"));

  let yAxis = d3.svg.axis()
      .scale(y)
      .orient("left")
      .ticks(10);

      data.forEach(function(d) {
        d.date = new Date(d.date);
        d.value = +d.value;
    });

  let chartDiv = document.getElementById("timeline-viz");
  let svg = d3.select(chartDiv).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 + ")");  

  x.domain(data.map(function(d) { return d.date; }));
  y.domain([0, d3.max(data, function(d) { return d.count; })]);

  svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
.selectAll("text")
  .style("text-anchor", "end")
  .attr("dx", "-.8em")
  .attr("dy", "-.55em")
  .attr("transform", "rotate(-90)" );

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
.append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Value ($)");

  svg.selectAll("bar")
  .data(data)
  .enter().append("rect")
  .style("fill", "steelblue")
  .attr("x", function(d) { return x(d.date); })
  .attr("width", x.rangeBand())
  .attr("y", function(d) { return y(d.count); })
  .attr("height", function(d) { return height - y(d.count); });

但我需要制作类似require sample chart

的图表

我是日期时间条形图的新手,我们非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您只想将厚格式从月/年更改为日/月?可以通过在x轴声明中更改thickFormat来实现,如:

.tickFormat(d3.time.format("%d/%m"));

这是更新的fiddle

您可以在D3.js documentation中找到所有可能的日期时间格式。