简体   繁体   English

d3 v4 X轴刻度

[英]d3 v4 X-axis ticks

Having a brutal time trying to illustrate a historic S&P 500 performance chart year-by-eyar. 有一段残酷的时间试图逐年展示历史性的标准普尔500指数表现图表。 No matter what I try, the X-axis "ticks()" method is ignored and simply uses a value of 1. Which is very hard to see. 无论我尝试什么,X轴“ticks()”方法都被忽略,只使用值1.这是很难看到的。

var margin = {top: 20, right: 20, bottom: 70, left: 40},
    width = $('#sp501').width() - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// Parse the date / time
var parseDate = d3.timeParse("%Y-%m");

var x = d3.scaleBand().range([0, width], .05);

var y = d3.scaleLinear().range([height, 0]);

var xAxis = d3.axisBottom(x)
        .tickFormat(d3.timeFormat("%Y"))
        .ticks(10); // I can't figure out why this is ignored!

var yAxis = d3.axisLeft(y)
    .ticks(10);

var svg = d3.select("#sp501")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", 
          "translate(" + margin.left + "," + margin.top + ")");

d3.csv("data/sp500-historical.csv", function(error, data) {

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

    x.domain(data.map(function(d) { return d.date; }));
    y.domain([-60, 60]);

  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)" );

The data is in a convention format: 数据采用常规格式:

date,value
1928-01,43.81
1929-01,-8.30
1930-01,-25.12
1931-01,-43.84
1932-01,-8.64
1933-01,49.98
1934-01,-1.19
1935-01,46.74
1936-01,31.94

And I've tried converting the dates to just integer years to see if that works, to no avail. 我已经尝试将日期转换为整数年,看看是否有效,但无济于事。

Am I nuts or is something wrong with X-axis ticks using dates? 我是疯了还是使用日期的X轴刻度有问题?

Thanks! 谢谢!

While not setting the ticks explicitly, this snippet worked to feed the extent to d3 before the axisBottom call, which then cleaned up the display. 虽然未明确设置刻度,但此片段在axisBottom调用之前将范围提供给d3,然后清除显示。

svg.append("g")
  .attr("class", "e4rAxis")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM