簡體   English   中英

在d3js中,是否可以在x軸上轉換固定范圍的值?

[英]In d3js, is it possible to transition a fixed range of values on x-axis?

我希望創建一個帶過渡的折線圖。 因此,對於第一步,我希望簡單地繪制軸並移動x軸。 x軸有0-15作為值,我希望這些值繼續在循環中移動..我從這個代碼獲得幫助,我通過stackoverflow: http//jsfiddle.net/aggz2qbn/

這是我的代碼:

var t = 1, maxval;
var i, n = 40;
var duration = 750;
function refilter(){

var margin = {top: 10, right: 10, bottom: 20, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.linear()
    .domain([1, 15])
    .range([0, width]);

var y = d3.scale.linear()
    .domain([0, maxval])
    .range([height, 0]);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// extra svg to clip the graph and x axis as they transition in and out
var graph = g.append("svg")
    .attr("width", width)
    .attr("height", height + margin.top + margin.bottom);   

var xAxis = d3.svg.axis().scale(x).orient("bottom");
var axis = graph.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(x.axis=xAxis);

g.append("g")
    .attr("class", "y axis")
    .call(d3.svg.axis().scale(y).orient("left"));

tick();

function tick() {
    t++;
    if(t>=15)
        t=1;
    else if(t<=15)
    {   
        x.domain([t,15]);
        axis.transition()
        .duration(500)
        .ease("linear")
        .call(xAxis)
        .each("end", tick);
    }
     // slide the x-axis left

}
}

x軸上的值確實會移動,但不會以重復的方式移動,相反,它們只是將1到15伸展。任何人都可以幫助我嗎?

您的tick函數將域設置為:

[1,15]
then
[2,15]
then
[3,15]
etc...

這是更接近結束的縮放。 你想要的是滾動效果(比如N為5個刻度):

[1,5]
then
[2,6]
then
[3,7]
etc...

所以:

function tick() {
  var curD = x.domain(); // get current domain   
  if (curD[1] >= 15){ // at 15 reset to 1,5
     curD[0] = 0;
     curD[1] = n-1;
   }
  x.domain([curD[0]+1,curD[1]+1]); // increase both sides by one

  // slide the x-axis left
  axis.transition()
    .duration(1500)
    .ease("linear")
    .call(xAxis)
    .each("end", tick);
}

這里的例子。

評論的編輯

日期時間可以以相同的方式處理,但數學運算不同。 例如,滾動我的月份:

function tick() {
  var curD = x.domain();
  var newD = [curD[0].setMonth(curD[0].getMonth() + 1),
            curD[1].setMonth(curD[1].getMonth() + 1)]
  x.domain(newD);
  // slide the x-axis left
  axis.transition()
    .duration(1500)
    .ease("linear")
    .call(xAxis)
    .each("end", tick);
}

更新的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM