【问题标题】:more than one set of labels in protovis?protovis 中不止一组标签?
【发布时间】:2023-04-01 20:26:01
【问题描述】:

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

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();

【问题讨论】:

    标签: protovis


    【解决方案1】:

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

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

    您的代码中有几个问题:

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

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

    解决此问题的简单方法是仅在单个标记上链接方法。为此,您可以将父标记分配给一个变量,然后将该变量多次用于不同的子标记。您还可以将第一个 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/

    【讨论】:

    • 感谢 protovis 大师!一分给你,一分是无耻的奉承!
    猜你喜欢
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多