[英]Dynamic tickValues on time.scale in D3
I built a graph in D3, to show spending based on date time and amount of spending, but I can't dynamically set tickValues()
on my time.scale to show only ticks for data points. 我在D3中建立了一个图表,以根据日期时间和支出金额显示支出,但是我无法在tickValues()
上动态设置tickValues()
以仅显示数据点的价格变动。
My scale set up is: 我的秤设置为:
var dateScale = d3.time.scale()
.domain(d3.extent(newData, function(d) { return d.Date; }))
.range([padding, width - padding]);
var amountScale = d3.scale.linear()
.domain([0, d3.max(newData, function(d) { return d.Amount; })])
.range([window.height - padding, padding]);
// Define date Axis
var dateAxis = d3.svg.axis().scale(dateScale)
.tickFormat(d3.time.format('%a %d %m'))
.tickSize(100 - height)
.orient("bottom");
// Draw date Axis
svg.append("g")
.attr({
"class": "axis date-axis",
"transform": "translate(" + [0, height -padding] + ")"
}).call(dateAxis);
// Define amount Axis
var amountAxis = d3.svg.axis().scale(amountScale)
.tickSize(1)
.orient("left");
// Draw amount Axis
svg.append("g")
.attr({
"class": "axis amount-axis",
"transform": "translate(" + padding + ",0)"
}).call(amountAxis);
I've tried to set 我尝试设置
dateAxis.tickValues(d3.extent(newData, function(d) { return d.Date; }))
but this only returns min and max value for date axis. 但这只会返回日期轴的最小值和最大值。
Also tickValues()
doesn't accept newData
itself - what else I can try here? 另外tickValues()
本身不接受newData
我还能在这里尝试什么?
I want to achieve this: 我想实现这一目标:
to have only ticks highlighted, associated with corresponding data. 仅突出显示与相关数据相关的刻度线。
I ended up with creating new array of all date points out of my data, to pass it to tickValues()
method. 最后,我从数据中创建了所有日期点的新数组,然后将其传递给tickValues()
方法。 My code now is: 我的代码现在是:
var newData = toArray(uniqueBy(data, function(x){return x.Date;}, function(x, y){ x.Amount += y.Amount; return x; }));
// Create array of data date points
var tickValues = newData.map(function(d){return d.Date;});
// Sorting data ascending
newData = newData.sort(sortByDateAscending);
var dateScale = d3.time.scale()
.domain(d3.extent(newData, function(d) { return d.Date; }))
.range([padding, width - padding]);
var amountScale = d3.scale.linear()
.domain([0, d3.max(newData, function(d) { return d.Amount; })])
.range([window.height - padding, padding]);
// Define date Axis
var dateAxis = d3.svg.axis().scale(dateScale)
.tickFormat(d3.time.format('%d %m %Y'))
.tickValues(tickValues)
.orient("bottom");
So now whole graph looks as: 所以现在整个图看起来像:
I found this SO (@AmeliaBR) answer explaining tickValues()
function, and here is documentation for it too. 我发现这个SO(@AmeliaBR)答案解释了tickValues()
函数, 这也是它的文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.