0

我对尝试修剪并将一组数组移交给 Protovis 感到非常沮丧,这些数组只包含一组数据对象中的数字,看起来像下面这样,为每个对象绘制三个单独的饼图(pv.Wedge)......

myData = [{dept:"Accounting",sal:90000,equ:10000,trvl:267,extra:5000},
              {dept:"Sales",sal:20000,equ:10000,trvl:3049,extra:7000},
              {dept:"Consulting",sal:90000,equ:58000,trvl:983,extra:17000}];

从文档中,我被告知在 Protovis 中几乎不需要循环,但我似乎无法正确操作/解析 myData,所以我求助于显式循环。

我尝试了许多不同类型的循环,但我得到的最好的结果是在我希望饼图出现的空白区域下打印出数字。如果有人能给我暗示我应该做些什么来实现这一目标,我将不胜感激。目前我被困在 -

function getData(dept) {
   var getvals = new Array();
     for(idx in dept) {
       for(i in idx) {
           if(idx[i]=="^[0-9]+$") {
             getme.push(idx[i]); 
       }
   }      
 }
   return getvals;   

}

// myData = myData.map(function(d) {
//    var valonly = new Array();
//    for(key in d) {
//       if(isNaN(d[key])==false) {
//          valonly.push(d[key]);
//       }
//    }
//    return valonly;
// });


var vis = new pv.Panel()
  .width(w)
  .height(h)
  .data(getData(myData))
vis.add(pv.Wedge)
  //.data(pv.normalize(getData(myData)))
  .left(100) 
  .bottom(100)
  .outerRadius(r)
  .angle(function(d) d * 2 * Math.PI)
vis.add(pv.Label)
  .bottom(0)
  .left(100)
  .textAlign("center")
  //.text(data.dept + " - " + "total: " + hrsum);


vis.render();
4

1 回答 1

1

The following works. I worked with the data as you had it defined. It could be easier to work with if the values for the wedges were themselves in an array. That said, it was interesting teasing out the data from the object. def creates a local variable. I chose to use that for values and total rather than normalize as it then made it easier to add lables later on. There's possibly a more elegant way of doing this, but you should be able to see one approach without looping.

var myData = [{dept:"Accounting",sal:90000,equ:10000,trvl:267,extra:5000}, 
    {dept:"Sales",sal:20000,equ:10000,trvl:3049,extra:7000}, 
    {dept:"Consulting",sal:90000,equ:58000,trvl:983,extra:17000}]; 

var vis = new pv.Panel() 
    .width(200) 
    .height(200)
    .data(myData);

vis.add(pv.Wedge)
    .def("values", function(d) pv.entries(d).filter(function(e) !isNaN(e.value)))
    .def("total", function(d) pv.sum(this.values(), function(e) e.value))
    .data(function(d) this.values())
    .left(100)  
    .bottom(100) 
    .outerRadius(90)
    .angle(function(d) (d.value / this.total()) * 2 * Math.PI )
.anchor("center").add(pv.Label)
    .text(function(d) d.key);

vis.add(pv.Label)
    .bottom(0)
    .left(50) 
    .textAlign("center")
    .text(function(d) d.dept); 

vis.render(); 
于 2010-10-05T21:22:46.523 回答