4👍
✅
I have found the solution. For Chart.js 2.1.x onwards (it doesn’t work Chart.js 1.x.x), you can apply the dataset with custom option as shown below:
var options = {
scales:{
xAxes: [{ stacked: true }],
yAxes: [{ stacked: true }]
}
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
I’m using the chart js 2.2.1 gem from this source. The helper method from line 3-35 provides the insight on how to create stacked bar chart. Somehow it doesn’t have the option to input the data from the method given. So let’s override the helper method:
def chart2_bar id=nil, size=nil, data={}, options={}
html = "<canvas id=\"myChart_bar\" width=\"#{size[:width]}px\" height=\"#{size[:height]}px\"></canvas>".html_safe
script = javascript_tag do
<<-END.html_safe
var ctx = document.getElementById("myChart_bar");
var data = "#{data.to_json}";
var options = "#{options.to_json}";
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
END
end
return html + script
end
The data must be in json format or else it would be treated as string format, and so error. You can create an instance variable and pass into the helper method as usual.
Wouldn’t say this is the perfect solution but it works well from generating html and also pdf (using wicked-pdf).
Source:stackexchange.com