1

我想在图表上同时显示值和数据类别。这是一个条形图,我希望将数据值和字符串打印在条形左侧的列中:

A 1 #
B 3 ###

我尝试将两个 add(pv.Label) 调用链接到我的图表上,但它似乎什么也没做 - 第二个标签集没有添加。这甚至可以用 protovis 完成吗?有什么建议吗?

vis = new pv.Panel()
.def("j", -1)
.width(800)
.height(50)
.right(3);

vis.add(pv.Bar)
.data(wData)
.bottom(0)
.width(20)
.height(function(d) d[1] * 1.2)
.left(function() this.index * 27)
.fillStyle(function() vis.j() == this.index ? "orange" : "steelblue")
.add(pv.Label)  **// does nothing!!**
.bottom(0)
.textAlign("center")
.textStyle("white")
.text(function(d) d[0] )
.event("mouseover", function() vis.j(this.index))
.event("mouseout", function() vis.j(-1))
.anchor("top").add(pv.Label)
.visible(function() vis.j() >= 0)
.textStyle("white")
.text(function(d) d[1]);
vis.render();
4

1 回答 1

2

当我尝试这个时,我确实看到了这两个标签。但是这里有几件事可以解决。关键点是,当您像这样链接方法时,当您add()使用新标记时,您会更改以下方法调用的上下文,例如:

vis.add(pv.Bar)
    // this applies to the Bar
    .width(10)
  .add(pv.Label)
    // this applies to the label
    .top(5);

您的代码中有几个问题:

  • 您的event()处理程序附加到标签,而不是栏 - 不幸的是,标签无法在 Protovis 中接收事件。

  • 您的第二个标签附加到第一个标签。虽然这实际上似乎有点作用,但最好避免它 - 你真的希望它连接到酒吧。

解决此问题的简单方法是仅在单个标记上链接方法。为此,您可以将父标记分配给一个变量,然后将该变量多次用于不同的子标记。您还可以将第一个 Label 直接附加到 Bar,而不是锚点 - 将其附加到锚点通常会给您带来更可预测的结果。

更新代码:

// make a new variable to refer to the bars
var bars = vis.add(pv.Bar)
    .data(wData)
    .bottom(0)
    .width(20)
    .height(function(d) d[1] * 1.2)
    .left(function() this.index * 27)
    .fillStyle(function() vis.j() == this.index ? "orange" : "steelblue")
    // you need to move the events up to apply 
    // to the bar - labels can't receive events, 
    // and the index will always be 0
    .event("mouseover", function() vis.j(this.index))
    .event("mouseout", function() vis.j(-1));

// now add each label to the bars
bars.anchor('bottom').add(pv.Label)
    .bottom(0)
    .textAlign("center")
    .textStyle("white")
    .text(function(d) d[0] );

// and again
bars.anchor("top").add(pv.Label)
    .visible(function() vis.j() >= 0)
    .textStyle("white")
    .text(function(d) d[1]);

这里有一个工作版本:http: //jsfiddle.net/nrabinowitz/ABmuq/

于 2011-07-09T14:56:31.753 回答