Distance and spacing Chart.JS

  • Is it possible to get even more space between the chart and the x axis?
  • Is it possible to get more space between the right side of the diagram and the end of the canvas area? I want to add some more elements to the canvas right next to the diagram, but this is not possible because the diagram occupies the entire width of the canvas so that it overlaps.

enter image description here

+6
source share
3 answers

X-axis offset vertical labels

The easiest way to do this is to add spaces to your x shortcuts. You can expand your chart type and redefine your initialization function to do this (increase 30 to something more if your shortcuts have already begun)

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); }, 

Edit: as noted in the comments, this also causes a horizontal shift, and the label no longer aligns with the x-axis markers.

Since both the x axis and the x marks are drawn by one function, and you do not have other variables that you may encounter (safely), this means that you will need to change the scale zoom function.

Find ctx.translate at the end of the drawing function and change it to

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

You will also have to adjust the end point a bit (which limits the y limits) so that an extra y offset will not overflow the labels with a chart (find the line that adjusts this in overriding the downward line for 2.).

Leaving a space on the right side

To make 2, you override the drawing function (in the advanced diagram) and change xScalePaddingRight. However, since this does not affect your horizontal grid lines, you must overlap the filled rectangle after the end of the draw. Your full drawing function will 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); } 

Original fiddle - https://jsfiddle.net/gvdmxc5t/

The script with the modified scale zoom function is https://jsfiddle.net/xgc6a77a/ (I turned off the animation in this, so that the endpoint shifts only once, but you can just hardcode it or add additional code so that it only runs one time)

+9
source

The 'tickMarkLength' option expands the grid lines outside the chart and pushes ticks down.

 xAxes: [ { gridLines: { tickMarkLength: 15 }, } ] 
+2
source

use this for chartjs 2.0

 scales: { xAxes: [{ barPercentage: 0.9, categoryPercentage: 0.55 }] 

Link

+2
source

Source: https://habr.com/ru/post/988668/


All Articles