本文介绍了如何修复d3折线图的timeScale?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我要解析的日期:

Here are the dates that I am parsing:

2010-12-31
2011-12-31
2012-12-31
2013-12-31
2014-12-31
2015-12-31
2016-12-31

这是我的代码:

 this.x  = d3.scaleTime().domain(d3.extent(this.dataArray, d => {return d[ this.xType ];})).range([ this.margin.left, this.width - this.margin.right ]);
        this.y0 = d3.scaleLinear().domain([ this.getMin(this.yType1, this.yType0), this.getMax(this.yType1, this.yType0) ]).range([ this.height, 0 ]);
        this.y1 = d3.scaleLinear().domain([ this.getMin(this.yType1, this.yType0), this.getMax(this.yType1, this.yType0) ]).range([ this.height, 0 ]);

        this.xAxis      = d3.axisBottom(this.x);
        this.yAxisLeft  = d3.axisLeft(this.y0).ticks(5);
        this.yAxisRight = d3.axisRight(this.y1).ticks(5);

问题在于,第一个日期(2010)从x轴被截断,并且在末尾添加了另一个刻度线,但是该图表绘制正确.

The problem is that the first date (2010) is being truncated from the x-axis and an additional tick is being added in the very end, however the chart is drawn right.

如果将.nice(this.dataArray.length)添加到this.x = ...,则2010年将在末尾加上2017年.

If I add .nice(this.dataArray.length) to this.x = ..., the year 2010 is added with 2017 at the very end.

如何解决此问题?谢谢.

How can I fix this problem? Thank you.

推荐答案

您可以map您的数据:

var ticks = data.map((d)=>d);

并在您的tickValues中使用此数组:

And use this array in your tickValues:

var axis = d3.axisBottom(scale)
    .tickValues(ticks);

这是一个演示:

var width = 500,
    height = 100;

var svg = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

var parse = d3.timeParse("%Y-%m-%d");

var data = ["2010-12-31",
    "2011-12-31",
    "2012-12-31",
    "2013-12-31",
    "2014-12-31",
    "2015-12-31",
    "2016-12-31"
];

data.forEach((d, i, a) => a[i] = parse(d));

var ticks = data.map((d) => d)
var format = d3.timeFormat("%Y")

var scale = d3.scaleTime()
    .domain(d3.extent(data, d => d)).range([20, width - 20]);

var axis = d3.axisBottom(scale).tickValues(ticks).tickFormat((d) => format(d));

var gX = svg.append("g")
    .attr("transform", "translate(0,50)")
    .call(axis);
<script src="https://d3js.org/d3.v4.min.js"></script>

这篇关于如何修复d3折线图的timeScale?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:21