d3.js无法使用一般更新模式和转换 [英] d3.js unable to use general update pattern and transition

查看:130
本文介绍了d3.js无法使用一般更新模式和转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我一些帮助这个d3.js问题吗?我试图遵循M.博斯托克的一般更新模式。



我不是使用列和行,而是绘制线。



程序显示两种模式,32条线与
g组合在一起,我假设。



我想要两组线,以显示一个在另一个之上,一个集通过样式更改为不透明度消失,或



将剩余的一组线定位在相同的位置
在第一组消失后的第一组线(原点为0.0)。



我认为问题是如何用g分组,但am
不确定。我尝试了各种方法附加到divs,容器,
和使用transform,translate,但没有什么工作。我试过
更改容器的大小,这也没有工作。



我认为svgs正在删除确定后,过渡,但我不
了解如何上移第二组行。



示例在jsfiddle:



https://jsfiddle.net/wheatgrass/t3bgcxhu/



感谢您的帮助。我很喜欢学习d3.js。

 < script> 
var num = 0;

var width = 660,
height = 25;

var radius = 2;

d3.select(body)。selectAll(h1)。data([{}])
.enter()。insert(h1)。html这里的一些文本)
var svg = d3.select(#svgcontainer)。append(svg)
.attr(width,width)
.attr ,height)
.append(g)
var g = svg.append(svg:g)
.attr(transform );

function getpatterndata(num){
if(num == 1){
var pdata = cellular(); }
else {pdata = cellular2(); }
console.log(pdata,pdata);

return pdata;
}

function makelines(datas){

var entries = d3.entries(datas);

var thelines = [];
var oneline = [];

entries.forEach(function(d){
var line = d.value.split();
thelines.push(line);
} );
//console.log(\"thelines,thelines);
return thelines;
}

函数更新(thelines,num){

// DATA JOIN
//使用旧元素加入新数据(如果有)。

//和UPDATE
for(i = 0; i

var oneline = thelines.pop );

//将行添加到容器
var sampleSVG = d3.select(body)
.append(svg)
.attr(width ,660)
.attr(height,10);

var circles = sampleSVG.selectAll(circle)
.data(oneline)
.enter()
.append(circle);



var circleAttributes = circles
.attr(cx,function(d,i){return(i * 10)})
.attr(cy,3)
.attr(transform,translate(30,+(0)+))
.transition $ b .attr(r,function(d,i){if(+ d == 1)
{return r = 3;} else {return r = 2;}})
。如果(+ d === 0){returnColor =lightblue;
} else if(+ d == = 1){returnColor =red;
} else if(+ d === 0){returnColor =green;}
return returnColor;
})
.transition(3000).delay(2000)
.attr(opacity,0.01)
.transition()。remove

}

}

函数update2(thelines,num){

//数据JOIN
//使用旧元素加入新数据(如果有)。

//和UPDATE
for(i = 0; i // for(i = thelines.length; i> = 0 ; i--){

var oneline = thelines.pop();

//将行添加到容器
var sampleSVG = d3.select(body)
.append(svg)
.attr ,660)
.attr(height,10)
.attr(transform,translate(0,0)

var circles = sampleSVG.selectAll(body)
.data(oneline)//将在线
.enter()
.append );


var circleAttributes = circles
.attr(cx,function(d,i){return(i * 10)})
.attr cy,3)
.attr(transform,translate(30,0))
.transition()。duration(2000)
.attr (d,i){if(+ d == 1)
{return r = 3;} else {return r = 2;}})
.style {
var returnColor;
if(+ d === 0){returnColor =lightblue;
} else if(+ d === 1){returnColor =red
} else if(+ d === 0){returnColor =green;}
return returnColor;
});
}
}

//初始显示。
var initialpattern = [];
var secpattern = [];
initialpattern = getpatterndata(2);

var thepatternrows = [];
thepatternrows = makelines(initialpattern);



update(thepatternrows,2);


secpattern = getpatterndata(1);

thepatternrows = makelines(secpattern);

update2(thepatternrows,1);

解决方案>

我尝试看看你的jsfiddle,但d3资源似乎没有正确加载(控制台日志一些错误加载不是https资源)。
我创建了一个plunker:
http://plnkr.co/edit/ UnOiooAFsprAYDQcyNFi?p =预览

  var num = 0; 

var width = 660,
height = 800;

var radius = 2;

d3.select(body)。selectAll(h1)。data([{}])enter()
.insert(h1)。html这里的一些文本)
var svg = d3.select(#svgcontainer)。append(svg)
.attr(width,width)
.attr ,height)
.append(g);
var g = svg.append(svg:g)
.attr(transform,translate(0,0)

function getpatterndata(num){
if(num == 1){
var pdata = cellular();
} else {
pdata = cellular2();
}
console.log(pdata,pdata);

return pdata;
}

function makelines(datas){

var entries = d3.entries(datas);

var thelines = [];
var oneline = [];

entries.forEach(function(d){
var line = d.value.split();
thelines.push(line);
} );
console.log(thelines,thelines);
return thelines;
}

函数更新(thelines,num){

// DATA JOIN
//使用旧元素加入新数据(如果有)。
console.log(thelines)
//和UPDATE
for(i = 0; i // for(i = thelines。 length; i> = 0; i--){

var oneline = thelines.pop();
console.log(oneline);
//将行添加到容器
var circles = g
.selectAll(。dummy)
.data(oneline)//将在线
.enter ()
.append(circle)
.classed('first-update',true);

//console.log(\"inside update,oneline,oneline);


var circleAttributes = circles.attr(cx,function(d,idx){
var x = idx * 10;
console.log x:',x)
return x;
})
.attr(cy,function(d,idx){
var y =(i + 1) 10;
console.log('y:',y)

return y;
})
.attr('r',2)
.attr(transform,translate(30,+(0)+))
.transition()。duration(2000)
.attr(r,function ,i){
if(+ d == 1){
return 3;
} else {
return 2;
}
})
.style(fill,function(d){
var returnColor;
if(+ d === 0){
returnColor =lightblue;
} else if(+ d === 1){
returnColor =red;
} else if(+ d === 0){
returnColor =green;

return returnColor;
})
.transition(3000)
.delay(2000)
.attr(opacity,0.01)
。transition();
//。remove();

}

} //结束函数

函数update2(thelines,num){

//数据JOIN
//使用旧元素加入新数据(如果有)。

//和UPDATE
for(i = 0; i // for(i = thelines.length; i& 0; i--){

var oneline = thelines.pop();

//将行追加到容器
// var sampleSVG = d3.select('svg');
var circles = g //.selectAll(\"body)
.selectAll('。dummy')
.data(oneline)
//将在线
.enter()
.append(circle);
console.log(inside update,oneline,oneline);


var circleAttributes = circles.attr(cx,function(d,idx){
return(idx * 10);
})
.attr(cy,function(d,idx){return i * 10;})
.attr(transform,translate(30,0))
.transition .duration(2000)
.attr(r,function(d,i){
if(+ d == 1){
return 3;
} else {
return 2;
}
})
.style(fill,function(d){
var returnColor;
if(+ d = == 0){
returnColor =lightblue;
} else if(+ d === 1){
returnColor =red;
} d === 0){
returnColor =green;
}
return returnColor;
});
}
}

//初始显示。
var initialpattern = [];
var secpattern = [];
initialpattern = getpatterndata(2);

var thepatternrows = [];
thepatternrows = makelines(initialpattern);

console.log(thepatternrows,thepatternrows);
update(thepatternrows,2);

//d3.select('div')。attr(class,。inside)。selectAll(*)。remove();

secpattern = getpatterndata(1);

thepatternrows = makelines(secpattern);

update2(thepatternrows,1);



//#myc11a.js

//随机化,并返回一个由空格分隔的大字符串列表
function cellular2(){
//这与其他模式输入相同,除了它随机化了
//邻居。
//我试图从python翻译为d3.js javascript
// def ca():
//'''使用Python的Celluar自动机 - K. Hong'''
//#64 Boolean - True(1):'*'
//# - False(0):' - '
//#Rule - 当前单元格的状态为True
//#如果上一步中两个邻居中只有一个为True('*')
//#,否则当前单元格状态为False(' - ')

//#list代表64个单元格的当前状态
var ca = [];
for(i = 0; i <64; i ++){

var arval = Math.round(Math.random());
ca.push(arval);
}

//#new细胞值

// dic = {0: - ,1:*}


//#initial draw - step 0
// print''.join([dic [e] for e in ca_new])
//console.log('initial ca ',ca);

var ca_next_string ='';
var castring = ca.valueOf();
//console.log(\"initial castring,castring);
var castring2 = ca.join();
//console.log(\"initial castring2,castring2);


var ca_lol0 = [];
ca_lol0.push(castring2);
//ca_lol0.push(\"\\\
);

var ca_new = ca;


castring =''
castring2 =''
//其他31个步骤
//循环通过0到63并存储当前单元格状态in ca_new list
var ca_next = [];
var step = 1;
while(步骤< 32){
ca_new = [];
//循环通过0到63,并将当前单元格状态存储在ca_new列表中
for(var i = 0; i <64; i ++){
//相邻小区状态
if(i> 0&< 63){
if(ca [i-1] == ca [i + 1]){
ca_new .push(0);
} else {
ca_new.push(1);
}
}

//最左边的单元格:检查第二个单元格
else if(i == 0){
if(ca [ 1] == 1){
ca_new.push(1);
} else {
ca_new.push(0);
}
}

//最右边的单元格:检查第二个到最后一个单元格
else if(i == 63){
if (ca [62] == 1){
ca_new.push(1);
} else {
ca_new.push(0);
}
}


castring0 = ca_new.join();
castring20 = ca_new.concat(\\\
);
} // end of for

//绘制当前单元格状态
//这一个包含0,1

ca_lol0.push(castring20。 join(''))
//ca_lol0.push(castring20)
//ca_lol0.push('\ n')

//更新单元格列表
ca = ca_new;
ca_next = [];
step = step + 1;
} // end of while

// console.log(final list of strings,ca_lol0);
console.log(random of neighbors);
// return castring20;
return ca_lol0;

}

//myc11.js
//返回一个由空格分隔的大字符串列表
function cellular(){
//我试图从python翻译为d3.js javascript
// def ca():
//'''使用Python的Celluar自动机 - K. Hong'''
/ /#64 Boolean - True(1):'*'
//# - False(0):' - '
//#Rule - 当前单元格值的状态为True
//#如果上一步中两个邻居中只有一个为True('*')
//#,否则当前单元格状态为False(' - ')

/ /#list代表64个单元的当前状态
var ca = [
0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0
];

//#new细胞值

// dic = {0: - ,1:*}

$ b b //#initial draw - step 0
// print''.join([dic [e] for e in ca_new])
//console.log('initial ca',ca);

var ca_next_string ='';
var castring = ca.valueOf();
//console.log(\"initial castring,castring);
var castring2 = ca. join();
//console.log(\"initial castring2,castring2);


var ca_lol0 = [];
ca_lol0.push(castring2);
//ca_lol0.push(\"\\\
);

var ca_new = ca;


castring =''
castring2 =''
//其他31个步骤
//循环通过0到63并存储当前单元格状态in ca_new list
var ca_next = [];
var step = 1;
while(步骤< 32){
ca_new = [];
//循环通过0到63,并将当前单元格状态存储在ca_new列表中
for(var i = 0; i <64; i ++){
//相邻小区状态
if(i> 0&< 63){
if(ca [i-1] == ca [i + 1]){
ca_new .push(0);
} else {
ca_new.push(1);
}
}

//最左边的单元格:检查第二个单元格
else if(i == 0){
if(ca [ 1] == 1){
ca_new.push(1);
} else {
ca_new.push(0);
}
}

//最右边的单元格:检查第二个单元格到最后一个单元格
else if(i == 63){
if (ca [62] == 1){
ca_new.push(1);
} else {
ca_new.push(0);
}
}


castring0 = ca_new.join();
castring20 = ca_new.concat(\\\
);
} // end of for

//绘制当前单元格状态
//这一个包含0,1

ca_lol0.push(castring20。 join(''))
//ca_lol0.push(castring20)
//ca_lol0.push('\ n')

//更新单元格列表
ca = ca_new;
ca_next = [];
step = step + 1;
} // end of while

// console.log(final list of strings,ca_lol0);
console.log(static assigned neighbor);
// return castring20;
return ca_lol0;

}

我注意到的第一件事是你创建一个svg你的更新循环的每次迭代。此步骤不是必需的,因为您正在顶部创建您的svg,还有一组用于存储您的圈子(或我猜猜)。



对于更新模式,这里是它的工作原理(对我的理解):




  • 你必须选择要更新的元素的类型上面:selectAll('。dummy'))

  • 您设置要绑定的数据(.data(oneline))


  • 退出并删除



现在在上面的代码中,我在绑定到数据之前使用了一个.dummy选择器,以避免选择现有对象。正确的方法是使用.selectAll('circle'),但在这种情况下,你只能得到一行圆,因为每次都会重新选择现有的圆。这与你自己循环的事实有关。我将尝试直接绑定到原始集合,并尝试正确使用回调函数来计算cx和cy。我会自己做,我甚至创建一个对象的数组,具有属性x和y,这将让我很容易建立我的圈子(但这是一个个人的数据设计选择)。



另外,在循环中使用变量i和在回调函数中用作计算cx和cy的索引器,这可能会导致冲突。



<我希望这是清楚(呃),它有助于;否则我将尝试详细阐述所需要的点。


Would someone please give me some help with this d3.js problem? I am trying to follow the M. Bostock 'General Update Pattern'. I have done research trying to get a solution but not getting anywhere.

Instead of using columns and rows, I am drawing lines.

The program displays two patterns which are 32 lines grouped together with "g", I assume.

I want the two groups of lines to either display one on top of the other, with one set disappearing via style changes to opacity, or

have the remaining set of lines be positioned in the same place as the first set of lines (with an origin of 0.0) after the first set disappears.

I think the problem is with how these are being grouped with "g" but am not sure. I've tried various methods of appending to divs, containers, and using the transform, translate, but nothing is working. I've tried changing the sizes of the containers and this did not work, either.

I think the svgs are being removed ok after the transition, but I don't understand how to "move up" the second set of lines.

The sample is at jsfiddle:

https://jsfiddle.net/wheatgrass/t3bgcxhu/

Thanks for any help. I am enjoying learning about d3.js.

<script>
var num = 0;

var width = 660,
   height = 25;

var radius = 2;

d3.select("body").selectAll("h1").data([{}])
  .enter().insert("h1").html("Some text here")
var svg = d3.select("#svgcontainer").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
var g = svg.append("svg:g") 
    .attr("transform", "translate(0, 0)") ;

function getpatterndata(num) {
if (num == 1)  {
    var pdata = cellular(); }
else { pdata = cellular2(); }
console.log("pdata",pdata);

return pdata;
}

function makelines(datas) {

var entries = d3.entries(datas);

var thelines = [];
var oneline = [];

entries.forEach( function (d) {
var line = d.value.split(" ");
    thelines.push(line);
  });
//console.log("thelines", thelines);
return thelines;
}

function update(thelines,num) {

 // DATA JOIN
 // Join new data with old elements, if any.

 // and UPDATE
 for (i =0; i< thelines.length; i++) {


var oneline = thelines.pop();

//append lines to container
   var sampleSVG = d3.select("body")
    .append("svg")
    .attr("width", 660)
    .attr("height", 10);    

var circles = sampleSVG.selectAll("circle")
                      .data(oneline) 
                   .enter()
                      .append("circle");



var circleAttributes = circles
                   .attr("cx", function(d,i) {return (i*10)} )
                   .attr("cy", 3)
                   .attr("transform", "translate(30," + (0) + ")")
           .transition().duration(2000)
           .attr("r", function(d,i) { if (+d  == 1)
                 { return r=3;  } else { return r = 2;}})
                   .style("fill", function(d) {
                     var returnColor;
                     if (+d === 0) { returnColor = "lightblue";
                     } else if (+d === 1) { returnColor = "red";
                     } else if (+d === 0) { returnColor = "green"; }
                     return returnColor;
                   })
                  .transition(3000).delay(2000)
      .attr("opacity", 0.01)
     .transition().remove();

}

}

function update2(thelines,num) {

// DATA JOIN
// Join new data with old elements, if any.

// and UPDATE
for (i =0; i< thelines.length; i++) {
 //for (i = thelines.length; i >= 0;  i--) {

var oneline = thelines.pop(); 

//append lines to container
var sampleSVG = d3.select("body")
    .append("svg")
    .attr("width", 660)
    .attr("height", 10)    
    .attr("transform", "translate(0, 0)") ;

var circles = sampleSVG.selectAll("body")
                      .data(oneline) //will be oneline
                   .enter()
                      .append("circle");


var circleAttributes = circles
                   .attr("cx", function(d,i) {return (i*10)} )
                   .attr("cy", 3)
                   .attr("transform", "translate(30,0)")
           .transition().duration(2000)
           .attr("r", function(d,i) { if (+d  == 1)
                 { return r=3;  } else { return r = 2;}})
                   .style("fill", function(d) {
                     var returnColor;
                     if (+d === 0) { returnColor = "lightblue";
                     } else if (+d === 1) { returnColor = "red";
                     } else if (+d === 0) { returnColor = "green"; }
                     return returnColor;
                   });
}
}

// The initial display.
var initialpattern = [];
var secpattern = [];
initialpattern = getpatterndata(2);

var thepatternrows = [];
thepatternrows = makelines(initialpattern);



update(thepatternrows,2);


secpattern = getpatterndata(1);

thepatternrows = makelines(secpattern);

update2(thepatternrows,1);

解决方案

I tried to have a look at you jsfiddle, but d3 resource does not seem to load properly (console logs some mistakes about loading not-https resource). I created a plunker: http://plnkr.co/edit/UnOiooAFsprAYDQcyNFi?p=preview

var num = 0;

var width = 660,
  height = 800;

var radius = 2;

d3.select("body").selectAll("h1").data([{}]).enter()
  .insert("h1").html("Some text here")
var svg = d3.select("#svgcontainer").append("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g");
var g = svg.append("svg:g")
  .attr("transform", "translate(0, 0)");

function getpatterndata(num) {
  if (num == 1) {
    var pdata = cellular();
  } else {
    pdata = cellular2();
  }
  console.log("pdata", pdata);

  return pdata;
}

function makelines(datas) {

  var entries = d3.entries(datas);

  var thelines = [];
  var oneline = [];

  entries.forEach(function(d) {
    var line = d.value.split(" ");
    thelines.push(line);
  });
  console.log("thelines", thelines);
  return thelines;
}

function update(thelines, num) {

  // DATA JOIN
  // Join new data with old elements, if any.
console.log(thelines)
  // and UPDATE
  for (i = 0; i < thelines.length; i++) {
    //for (i = thelines.length; i >= 0;  i--) {

    var oneline = thelines.pop();
console.log(oneline);
    //append lines to container
    var circles = g
      .selectAll(".dummy")
      .data(oneline) //will be oneline
      .enter()
      .append("circle")
      .classed('first-update',true);

    //console.log("inside update,oneline", oneline);


    var circleAttributes = circles.attr("cx", function(d, idx) {
      var x= idx*10;
      console.log('x: ',x)
      return x;
    })
      .attr("cy", function(d, idx) {
        var y = (i + 1) * 10;
        console.log('y: ',y)

        return y;
      })
      .attr('r',2)
      .attr("transform", "translate(30," + (0) + ")")
      .transition().duration(2000)
      .attr("r", function(d, i) {
        if (+d == 1) {
          return 3;
        } else {
          return 2;
        }
      })
      .style("fill", function(d) {
        var returnColor;
        if (+d === 0) {
          returnColor = "lightblue";
        } else if (+d === 1) {
          returnColor = "red";
        } else if (+d === 0) {
          returnColor = "green";
        }
        return returnColor;
      })
      .transition(3000)
      .delay(2000)
      .attr("opacity", 0.01)
      .transition();
    //.remove();

  }

} //end function

function update2(thelines, num) {

  // DATA JOIN
  // Join new data with old elements, if any.

  // and UPDATE
  for (i = 0; i < thelines.length; i++) {
    //for (i = thelines.length; i >= 0;  i--) {

    var oneline = thelines.pop();

    //append lines to container
    //var sampleSVG = d3.select('svg');
    var circles = g //.selectAll("body")
      .selectAll('.dummy')
      .data(oneline)
    //will be oneline
    .enter()
      .append("circle");
    console.log("inside update,oneline", oneline);


    var circleAttributes = circles.attr("cx", function(d, idx) {
      return (idx * 10);
    })
      .attr("cy", function(d,idx){return i*10;})
      .attr("transform", "translate(30,0)")
      .transition().duration(2000)
      .attr("r", function(d, i) {
        if (+d == 1) {
          return 3;
        } else {
          return 2;
        }
      })
      .style("fill", function(d) {
        var returnColor;
        if (+d === 0) {
          returnColor = "lightblue";
        } else if (+d === 1) {
          returnColor = "red";
        } else if (+d === 0) {
          returnColor = "green";
        }
        return returnColor;
      });
  }
}

// The initial display.
var initialpattern = [];
var secpattern = [];
initialpattern = getpatterndata(2);

var thepatternrows = [];
thepatternrows = makelines(initialpattern);

console.log("thepatternrows", thepatternrows);
update(thepatternrows, 2);

//d3.select('div').attr("class",".inside").selectAll("*").remove();

secpattern = getpatterndata(1);

thepatternrows = makelines(secpattern);

update2(thepatternrows, 1);



//#myc11a.js

//randomized, and returns a big list of strings separated by a space
function cellular2() {
  // This is the same as the other pattern input except it randomizes
  // the neighbors.
  // My attempt to translate from python to d3.js javascript
  //def ca():
  //   ''' Celluar automata with Python - K. Hong'''
  //   # 64 Boolean - True(1) : '*'
  //   #            - False(0): '-'
  //   # Rule - the status of current cell vaue is True
  //   # if only one of the two neighbors at the previous step is True('*')
  //   # otherwise, the current cell status is False('-')

  //  # list representing the current status of 64 cells
  var ca = [];
  for (i = 0; i < 64; i++) {

    var arval = Math.round(Math.random());
    ca.push(arval);
  }

  //# new Cellular values

  //   dic = { 0:"-", 1: "*" }


  //# initial draw - step 0
  //print  ''.join( [dic[e] for e in ca_new])
  //console.log('initial ca',ca);

  var ca_next_string = '';
  var castring = ca.valueOf();
  //console.log("initial castring",castring);
  var castring2 = ca.join(" ");
  //console.log("initial castring2",castring2);


  var ca_lol0 = [];
  ca_lol0.push(castring2);
  //ca_lol0.push("\n");

  var ca_new = ca;


  castring = ''
  castring2 = ''
  // additional 31 steps
  // loop through 0 to 63 and store the current cell status in ca_new list
  var ca_next = [];
  var step = 1;
  while (step < 32) {
    ca_new = [];
    // loop through 0 to 63 and store the current cell status in ca_new list
    for (var i = 0; i < 64; i++) {
      // inside cells - check the neighbor cell state
      if (i > 0 && i < 63) {
        if (ca[i - 1] == ca[i + 1]) {
          ca_new.push(0);
        } else {
          ca_new.push(1);
        }
      }

      // left-most cell : check the second cell
      else if (i == 0) {
        if (ca[1] == 1) {
          ca_new.push(1);
        } else {
          ca_new.push(0);
        }
      }

      // right-most cell : check the second to the last cell
      else if (i == 63) {
        if (ca[62] == 1) {
          ca_new.push(1);
        } else {
          ca_new.push(0);
        }
      }


      castring0 = ca_new.join(" ");
      castring20 = ca_new.concat("\n");
    } //end of for

    //draw current cell state
    //this one contains 0,1

    ca_lol0.push(castring20.join(' '))
    //ca_lol0.push(castring20)
    //ca_lol0.push('\n')

    //update cell list
    ca = ca_new;
    ca_next = [];
    step = step + 1;
  } //end of while

  //           console.log("final list of strings",ca_lol0);
  console.log("pattern of randomized neighbors");
  // return castring20;
  return ca_lol0;

}

//myc11.js
//returns a big list of strings separated by a space
function cellular() {
  // my attempt to translate from python to d3.js javascript
  //def ca():
  //   ''' Celluar automata with Python - K. Hong'''
  //   # 64 Boolean - True(1) : '*'
  //   #            - False(0): '-'
  //   # Rule - the status of current cell vaue is True
  //   # if only one of the two neighbors at the previous step is True('*')
  //   # otherwise, the current cell status is False('-')

  //  # list representing the current status of 64 cells
  var ca = [
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  ];

  //# new Cellular values

  //   dic = { 0:"-", 1: "*" }


  //# initial draw - step 0
  //print  ''.join( [dic[e] for e in ca_new])
  //console.log('initial ca',ca);

  var ca_next_string = '';
  var castring = ca.valueOf();
  //console.log("initial castring",castring);
  var castring2 = ca.join(" ");
  //console.log("initial castring2",castring2);


  var ca_lol0 = [];
  ca_lol0.push(castring2);
  //ca_lol0.push("\n");

  var ca_new = ca;


  castring = ''
  castring2 = ''
  // additional 31 steps
  // loop through 0 to 63 and store the current cell status in ca_new list
  var ca_next = [];
  var step = 1;
  while (step < 32) {
    ca_new = [];
    // loop through 0 to 63 and store the current cell status in ca_new list
    for (var i = 0; i < 64; i++) {
      // inside cells - check the neighbor cell state
      if (i > 0 && i < 63) {
        if (ca[i - 1] == ca[i + 1]) {
          ca_new.push(0);
        } else {
          ca_new.push(1);
        }
      }

      // left-most cell : check the second cell
      else if (i == 0) {
        if (ca[1] == 1) {
          ca_new.push(1);
        } else {
          ca_new.push(0);
        }
      }

      // right-most cell : check the second to the last cell
      else if (i == 63) {
        if (ca[62] == 1) {
          ca_new.push(1);
        } else {
          ca_new.push(0);
        }
      }


      castring0 = ca_new.join(" ");
      castring20 = ca_new.concat("\n");
    } //end of for

    //draw current cell state
    //this one contains 0,1

    ca_lol0.push(castring20.join(' '))
    //ca_lol0.push(castring20)
    //ca_lol0.push('\n')

    //update cell list
    ca = ca_new;
    ca_next = [];
    step = step + 1;
  } //end of while

  //           console.log("final list of strings",ca_lol0);
  console.log("pattern of static assigned neighbors");
  // return castring20;
  return ca_lol0;

}

The first thing I noticed is that you create an svg at each iteration of your update loop. This step is not required, as you are creating your svg at the top, and a group to store your circles (or so I guess).

As for the update pattern,here is how it works (for what I understood):

  • you have to select the types of element you want to update ( in code above: selectAll('.dummy') )
  • you set the data you want to bind to ( .data(oneline) )
  • you do your operations (appending circles, setting their attributes, etc.)
  • you exit and you remove

Now in the code above, I used a .dummy selector before binding to data to avoid selecting existing objects. The proper way would be to use .selectAll('circle'), but in that case, you would only get one line of circles, as existing circles would be reselected every time. This is linked to the fact that you loop on the lines yourself. I would try to bind to the original collection directly, and try to use callback functions properly to compute cx and cy. Would I do it myself, I would even create an array of object with a property x and y that would let me build my circles easily (but that's a personnal data design choice).

Also, be careful for the use of the variable i in your loops and as an indexer in your callback functions for computing cx and cy, this could lead to conflicts.

I hope this is clear(er) and it helps; otherwise I will try to elaborate more on required points.

这篇关于d3.js无法使用一般更新模式和转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆