Chart.JS 间距和填充间距、Chart、JS

2023-09-09 21:04:58 作者:我の笑只為伱

是否可以在图表和 x 轴之间留出更多空间?是否可以在图表右侧和画布区域末端之间留出更多空间?我想在图表旁边的画布上添加更多元素,但这是不可能的,因为图表占据了整个画布宽度,因此会重叠.

推荐答案

x轴标签垂直移动

执行 1. 的最简单方法是在 x 标签中添加空格.您可以扩展您的图表类型并覆盖您的初始化函数来执行此操作(如果您的标签很长,则将 30 增加到更大的值)

The easiest way to do 1. is by adding spaces to your x labels. You can extend your chart type and override your initialize function to do this (increase 30 to something larger if your labels are long to start with anyway)

initialize: function(data){
    data.labels.forEach(function(item, index) {
        data.labels[index] += Array(Math.max(30 - item.length, 0)).join(" ");
    })
    Chart.types.Bar.prototype.initialize.apply(this, arguments);
},

编辑 :正如评论中所指出的,这也会导致水平偏移,并且标签末端不再与 x 轴标记对齐.

Edit : As pointed out in the comments, this causes a horizontal shift as well and the label ends no longer align with the x axis markers.

由于 x 轴和 x 标签都是在一个函数中绘制的,并且您没有其他变量可以(安全地)乱用,这意味着您必须更改实际的比例绘制函数.

Since both the x axis and the x labels are drawn in a single function and you have no other variables you can mess around with (safely) this means you'll have to change the actual scale draw function.

在绘图函数的末尾寻找一个 ctx.translate 并将其更改为

Look for a ctx.translate towards the end of the draw function and change it to

ctx.translate(xPos, (isRotated) ? this.endPoint + 22 : this.endPoint + 18);

您还必须稍微调整端点(驱动 y 限制),以便额外的 y 偏移不会导致标签溢出图表(在 2 的绘制覆盖中查找调整此值的线.).

You'll also have to adjust the endpoint (which drives the y limits) a bit so that the additional y offset doesn't cause the labels to overflow the chart (look for the line adjusting this in the draw override for 2.).

在右侧留出空隙

要执行 2,您覆盖您的绘图函数(在您的扩展图表中)并更改 xScalePaddingRight.但是,由于这不会影响您的水平网格线,因此您必须在绘制完成后覆盖一个填充的矩形.你完整的绘图函数应该是这样的

To do 2, you override your draw function (in your extended chart) and change xScalePaddingRight. However since this doesn't affect your horizontal grid lines you have to overlay a filled rectangle once your draw is complete. Your complete draw function would look like this

draw: function(){
    // this line is for 1.
    if (!this.scale.done) {
         this.scale.endPoint -= 20
         // we should do this only once
         this.scale.done = true;
    }
    var xScalePaddingRight = 120
    this.scale.xScalePaddingRight = xScalePaddingRight
    Chart.types.Bar.prototype.draw.apply(this, arguments);
    this.chart.ctx.fillStyle="#FFF";
    this.chart.ctx.fillRect(this.chart.canvas.width - xScalePaddingRight, 0, xScalePaddingRight, this.chart.canvas.height);
}

原始小提琴 - https://jsfiddle.net/gvdmxc5t/

使用修改后的 Scale 绘制功能 - https://jsfiddle.net/xgc6a77a/(我在这个中关闭了动画,所以端点仅移动一次,但您可以对其进行硬编码,或添加一些额外的代码,使其仅移动一次)

Fiddle with modified Scale draw function - https://jsfiddle.net/xgc6a77a/ (I turned off animation in this one so that the endpoint is shifted only once, but you could just hard code it, or add some extra code so that it's done only once)