在 Protovis 中绘制负数的正确方法是什么?

发布于 2024-11-25 16:01:34 字数 140 浏览 0 评论 0原文

对于最简单的用例,即值范围为 -10 到 10 的条形图,如何使用 Protovis JavaScript 图表库干净地对其进行编码?

我所说的“干净”是指将轴居中,显示 x 和 y 轴标签,并表示图表的列值,其中负值低于 y 轴,正值超过 y 轴。

For the simplest use case, a bar chart with values ranging from -10 to 10, how does one go about coding this cleanly using the Protovis JavaScript charting library?

By cleanly I mean centering the axis, showing x and y axis labels, and representing the column values of the chart where negative values fall below the y axis and positive values exceed the y axis.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你是年少的欢喜 2024-12-02 16:01:34

这是一个工作示例: http://jsfiddle.net/nrabinowitz/yk5By/3/

其中重要部分如下:

  • 制作一个从最小值到最大值的 x 轴刻度(在您的情况下,它将是pv.Scale.linear(-10,10).range(0,w); 在我的示例中,我根据数据计算最小值和最大值。

  • 条形宽度以数据距 0 的绝对距离为基础:

    .width(function(d) { return Math.abs(x(d) - x(0)); })
    
  • 然后根据基准是否为正或来调整 .left() 属性负面:

    .left(function(d) { return d > 0 ? x(0) : x(0) - this.width(); });
    
  • 因为我们使用简单的 x 轴刻度,所以添加轴标签非常简单:

    vis.add(pv.Label)
        .data(x.ticks()) // 你也可以在这里使用 pv.range(min, max, 1)
        .left(x);
    

Here's a working example: http://jsfiddle.net/nrabinowitz/yk5By/3/

The important parts of this are as follows:

  • Make an x-axis scale going from your min value to your max value (in your case, it would be pv.Scale.linear(-10,10).range(0,w); in my example, I calculate min and max based on the data).

  • Base the width of the bar on the absolute distance of the datum from 0:

    .width(function(d) { return Math.abs(x(d) - x(0)); })
    
  • Then adjust the .left() property based on whether the datum is positive or negative:

    .left(function(d) { return d > 0 ? x(0) : x(0) - this.width(); });
    
  • Because we're using a simple x-axis scale, the adding axis labels is super-easy:

    vis.add(pv.Label)
        .data(x.ticks()) // you could also use pv.range(min, max, 1) here
        .left(x);
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文