[Chartjs]-Chart.js horizontal line chart or modified horizontal bar chart

2👍

You first need to know that every information that you can edit about the chart is stored in the variable containing your chart (called myChart usually, but my2Bar in your fiddle).

If you want to globally change the graph, you will need to edit attributes in myChart.config.options.
If you want to change a specific chart, you will need to edit attributes in myChart.config.data.

In this case, you need to change a specific chart (which is the horizontal bar).


If you happen to check the logs of your graph, and go very deep in the config, you will finally see that bars in your chart are drawn using attributes stored in myChart.config.data.datasets[0]._meta[0].data[n]._model (n being the nth rectangle drawn, top to bottom).

Some attributes you can find there :

  • base : The X position where the rectangle is starting to be drawn (0 in your xAxe for instance).
  • x : The rectangle is being drawn until this X position.
  • height : The height of the drawn rectangle.
  • and so on …

To edit these values, you just need to loop in your different rectangles (the n in the above path).

But you just can’t do it manually on the config of your variable. If you do this, it won’t work since your chart is responsive (on resize, it will redraw the chart using the former options).


What you must use are Chart.js plugins.

Plugins let you handle all the events that are triggered while creating, updating, rendering your graph.

Then, in your beforeRender event (triggered after the initialisation, but before the drawing), you need to loop in your different rectangles to edit the values to affect how they will be drawn :

beforeRender: function(chart) {
    for (var i = 0; i < chart.config.data.datasets[0]._meta[0].data.length; i++) {
        // Change both `3` values to change the height & width of the point 
        chart.config.data.datasets[0]._meta[0].data[i]._model["base"] = chart.config.data.datasets[0]._meta[0].data[i]._model["x"] + 3;
        chart.config.data.datasets[0]._meta[0].data[i]._model["height"] = 3;
    }
}

Here is a jsFiddle with the final result.
Unfortunately, I wasn’t able to make round dots, instead of squared ones.

enter image description here


Update :

I have also made another jsFiddle where all the dots are linked together which makes it look like it is a horizontal line chart (can be improved of course, but it is a good start).

Leave a comment