score:2

Accepted answer

there are three things that need to be done to support this feature:

  1. use the category scale to calculate bar thickness in proportion to axis size (width for vertical, height for horizontal)
  2. override the #getpixelforvalue() method in the category scale so that the category widths reflect the variant thickness, instead of being uniform
  3. change the dimensions of the rectangles drawn by the controller using the values calculated by the scale

implemented these as a custom chart in this package: https://github.com/swayable/chartjs-chart-superbar using chart.js's new chart and new axes customization features.

solved (1) by adding behavior like this to the category scale:

getbarthickness(thicknesspercentage) {
  let thickness = thicknesspercentage * this._axissize(),
    spacing = this.options.spacing * 2

  return thickness - spacing
}

_axissize() {
  return this.ishorizontal() ? this.width : this.height
}

(2) is a bit more complicated because the pixel for each value in the category scale needs to take into account all of the various thicknesses for each previous item in the dataset when calculating the distance from the edge (left for horizontal, or top for vertical). otherwise the thicknesses of the categories in the axis will not match the thicknesses of the bars, and the category axis labels will not be centered on the bars.

relevant file for (1) and (2): https://github.com/swayable/chartjs-chart-superbar/blob/master/src/scale.thickcategory.js

(3) is solved by changing the relevant dimension in the element's _view and _model properties using the scale#getbarthickness() method above.

relevant file for (3): https://github.com/swayable/chartjs-chart-superbar/blob/master/src/mixin.barthickness.js


figured most of this out by reading the source code for chart.js, especially scale.category.js and core.datasetcontroller.js. also took some inspiration from the source code for chart.smith.js.


Related Query

More Query from same tag