在条形图中调整条形尺寸

时间:2018-01-03 15:03:43

标签: javascript canvas charts

我试图制作JavaScript条形图绘图仪。对于彼此足够接近的值,它的效果非常好。这是输入数组[1,2,3,4,5,6,7]的样子:1-7 bar chart

使用输入数组[1,2,3,4,5,6,1000]:enter image description here

我会说技术上这应该是正确的行为,因为它只显示大数字和其余数字之间的差异,但图表失去了它的清晰度。我无法弄清楚如何计算系数,这会将条形调整到适当的尺寸(相对于画布高度更高)。

以下是代码:

function barplot()
{
    this.load = function(canvas)
    {
        this.canvas = canvas;
        this.ctx = canvas.getContext("2d");
    },

    this.makebar = function(width, height, start)
    {
        this.ctx.beginPath();
        this.ctx.strokeStyle = "black";
        this.ctx.moveTo(start.x, start.y);
        this.ctx.lineTo(start.x,start.y-height);
        this.ctx.lineTo(start.x+width, start.y-height);
        this.ctx.lineTo(start.x+width,start.y);
        this.ctx.stroke();
        this.ctx.closePath();
    },

    this.plot = function(arr)
    {
        var width = this.canvas.width/arr.length;
        var max = Math.max.apply(null,arr);
        var min = Math.min.apply(null,arr);

        for(var i=0;i<arr.length;i++)    // Bar height generated here!
        {
            var coe = arr[i]/max;
            arr[i] = this.canvas.height*coe;  // The actual heights!
        }

        for(var i=0;i<arr.length;i++)
        {
            this.makebar(width, arr[i], {x:i*width,y:this.canvas.height});
        }
    }
}

如果有人想尝试,用法也很简单:

var b = new barplot();
b.load(your_canvas_element);
b.plot(array_of_numbers);

1 个答案:

答案 0 :(得分:1)

听起来我想要使用某种指数或对数刻度来表示值之间的相对大小。这将有效地为小数字提供“提升”。在您的代码中,您需要根据缩放方法而不是原始值来计算最小值和最大值。

选择看起来很好的方法&#39;对于你的情况是主观的,我不知道你正在绘制的数据的上下文,但这里有几个方法可能看起来的一些例子(使用Excel中的数据条绘制)。

  • 在第一行,我们有Math.pow(x, y)代表0&gt; y&gt; 1。
  • 在第二行,我们Math.pow(Math.log10(x + 1), y)代表y&gt; 1

Graphs

相关问题