How to add images as labels to Canvas Charts using chart.js - javascript

I am generating a chart.js canvas bar chart. What I am trying to do is, inside of the labels array, add images that go with each label, as opposed to just the text label itself. Here is the code for the chart: The json object that I am getting data from has an image url that I want to use to display the picture:
$.ajax({
method: "get",
url: "http://localhost:3000/admin/stats/show",
dataType: "json",
error: function() {
console.log("Sorry, something went wrong");
},
success: function(response) {
console.log(response)
var objectToUse = response.top_dogs
var updateLabels = [];
var updateData = [];
for (var i = 0; i < objectToUse.length; i+=1) {
updateData.push(objectToUse[i].win_percentage * 100);
updateLabels.push(objectToUse[i].title);
}
var data = {
labels: updateLabels,
datasets: [
{
label: "Top Winners Overall",
fillColor: get_random_color(),
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: get_random_color(),
highlightStroke: "rgba(220,220,220,1)",
data: updateData
}
]
};
var options = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 2,
};
var loadNewChart = new Chart(barChart).Bar(data, options);
}
});
If anyone has a solution it would be greatly appreciated!

I'm aware that this is an old post but since it has been viewed so many times, I'll describe a solution that works with the current Chart.js version 2.9.3.
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw images (icons) directly on the canvas using CanvasRenderingContext2D.
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
ctx.drawImage(images[index], x - 12, yAxis.bottom + 10);
});
}
}],
The position of the labels will have to be defined through the xAxes.ticks.padding as follows:
xAxes: [{
ticks: {
padding: 30
}
}],
Please have a look at the following runnable code snippet.
const labels = ['Red Vans', 'Blue Vans', 'Green Vans', 'Gray Vans'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png']
.map(png => {
const image = new Image();
image.src = png;
return image;
});
const values = [48, 56, 33, 44];
new Chart(document.getElementById("myChart"), {
type: "bar",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
ctx.drawImage(images[index], x - 12, yAxis.bottom + 10);
});
}
}],
data: {
labels: labels,
datasets: [{
label: 'My Dataset',
data: values,
backgroundColor: ['red', 'blue', 'green', 'lightgray']
}]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
padding: 30
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Chart.js v3+ solution to pie, doughnut and polar charts
With version 3 of Chart.js and the updated version of chart.js-plugin-labels, this is now incredbly simple.
in options.plugins.labels, add render: image and the nested array images with objects containing the properties src, width and height.
const data = {
labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5', 'Label 6', 'Label 7', 'Label 8'],
datasets: [{
label: 'Image labels',
// Making each element take up full width, equally divided
data: [100, 100, 100, 100, 100, 100, 100, 100],
backgroundColor: [
'rgba(255, 26, 104, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(0, 0, 0, 0.2)',
'rgba(20, 43, 152, 0.2)'
]
}]
};
const config = {
type: 'doughnut',
data,
options: {
plugins: {
// Accessing labels and making them images
labels: {
render: 'image',
images: [{
src: 'https://cdn0.iconfinder.com/data/icons/google-material-design-3-0/48/ic_book_48px-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn3.iconfinder.com/data/icons/glypho-free/64/pen-checkbox-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn1.iconfinder.com/data/icons/jumpicon-basic-ui-glyph-1/32/-_Home-House--256.png',
height: 25,
width: 25
},
{
src: 'https://cdn1.iconfinder.com/data/icons/social-media-vol-3/24/_google_chrome-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn0.iconfinder.com/data/icons/google-material-design-3-0/48/ic_book_48px-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn3.iconfinder.com/data/icons/glypho-free/64/pen-checkbox-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn1.iconfinder.com/data/icons/jumpicon-basic-ui-glyph-1/32/-_Home-House--256.png',
height: 25,
width: 25
},
{
src: 'https://cdn1.iconfinder.com/data/icons/social-media-vol-3/24/_google_chrome-256.png',
height: 25,
width: 25
},
]
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart').getContext('2d'),
config
);
.chartCard {
width: 100vw;
height: 500px;
display: flex;
align-items: center;
justify-content: center;
}
.chartBox {
width: 600px;
padding: 20px;
}
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://unpkg.com/chart.js-plugin-labels-dv#3.0.5/dist/chartjs-plugin-labels.min.js"></script>

Related

ChartJS Horizontal bars barely visible with 50 records on the Y axis

Is there a way to set the vertical thickness of the horizontal bars in ChartJS(3.7.0). Or change the zoom level or something?
I have a recordset with 50 rows which should show 50 horizontal bars. However when the chart is rendered. The lines representing the horizontal bars are barely visible.
I am using this config:
const config = {
type: 'bar',
data: chart_data,
options: {
maintainAspectRatio: false,
scales: {
yAxes: [{
barThickness: 20, // number (pixels) or 'flex'
maxBarThickness: 22 // number (pixels)
}]
},
indexAxis: 'y',
plugins: {
legend: {
position: 'right',
},
}
}
};
I am also setting the bar and max thickness in each dataset as well. Also set the height of the parent <div> which houses the <canvas> tag to a large value 3200px.
Thanks
Without seeing more of your code, it's almost impossible to find out, why the thickness of the bars in your chart is not what you expect.
The following points however are worth knowing when working with Chart.js v3:
scales.[x/y]Axes.barThickness was moved to dataset option barThickness
scales.[x/y]Axes.maxBarThickness was moved to dataset
option maxBarThickness
More details can be found in the 3.x Migration Guide or in the Chart.js v3 documentation here.
Please take a look at below runnable script and see how it could be done in your case.
const data = [...Array(50)].map(e => ~~(Math.random() * 20 + 1));
const colors = ['255, 99, 132', '54, 162, 235', '255, 206, 86', '231, 233, 237', '75, 192, 192', '151, 187, 205', '220, 220, 220', '247, 70, 74', '70, 191, 189', '253, 180, 92', '148, 159, 177', '77, 83, 96'];
new Chart('chart', {
type: 'bar',
plugins: [{
beforeLayout: chart => chart.options.scales.y1.labels = chart.data.datasets.filter((ds, i) => !chart.getDatasetMeta(i).hidden).map(ds => ds.label)
}],
data: {
datasets: data.map((v, i) => ({
label: i + 1,
data: [{ x: v, y: i }],
backgroundColor: 'rgba(' + colors[i % colors.length] + ', 0.4)',
borderColor: 'rgb(' + colors[i % colors.length] + ')',
borderWidth: 1,
categoryPercentage: 1
}))
},
options: {
indexAxis: 'y',
plugins: {
legend: {
position: 'right',
},
tooltip: {
callbacks: {
title: () => undefined
}
}
},
scales: {
y: {
},
y1: {
offset: true,
gridLines: {
display: false
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<canvas id="chart" height="600"></canvas>

Create space between legend and chart in charts.js [duplicate]

This question already has answers here:
Chart.js - Increase spacing between legend and chart
(13 answers)
Closed 1 year ago.
I am working with charts.js but I'm facing an issue. My legend and bar chart value overlaps a bit.
I am not able to resolve this issue, It would be appreciated if there is a solution to this issue
I have shared JS fiddle link below
https://jsfiddle.net/qh0yzmjf/1/
var ctx = document.getElementById("canvas").getContext("2d");
var nomi = [2017, 2018, 2019];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: nomi,
datasets: [{
label: 'PP PERVENUTI',
data: [50, 30, 45],
backgroundColor: "#8A0808",
fill: false,
borderColor: "#8A0808",
borderWidth: 3
},
{
label: 'PP EVASI',
data: [60, 45, 12],
backgroundColor: "#0B610B",
fill: false,
borderColor: "#0B610B",
borderWidth: 3
},
{
label: 'PI PERVENUTI',
data: [20, 25, 35],
backgroundColor: "#8A0886",
fill: false,
borderColor: "#8A0886",
borderWidth: 3
},
{
label: 'PI EVASI',
data: [10, 20, 30],
backgroundColor: "#0404B4",
fill: false,
borderColor: "#0404B4",
borderWidth: 3
}
]
},
options: {
legend: {
display: true,
position: "top"
},
hover: {
animationDuration: 0
},
animation: {
onComplete: function() {
var ctx = this.chart.ctx;
const chart = this.chart;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.fillStyle = "black";
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
if (chart.getDatasetMeta(i).hidden) {
return;
}
for (var i = 0; i < dataset.data.length; i++) {
for (var key in dataset._meta) {
var model = dataset._meta[key].data[i]._model;
ctx.fillText(dataset.data[i], model.x, model.y);
}
}
});
}
}
}
});
I have also shared my code above
I don't know how to create space between legend and chart, and help will be appreciated thanks
If I am not wrong, there isnt a configuration built by chart js to put padding between the labels and the chart,although, the padding to the labels are applied in wor format, this means that chart js applies padding between labels, on the other hand, you can apply padding between the title of the chart and the labels.
If you want padding between the tittle of the chart and the chart you can use the following code:
plugins: {
title: {
display: true,
text:'Historico Mensual',
},
legend: {
labels: {
padding: 100
}
}
},
Another solution it could be to change the position of the labels to the bottom with the following code:
options: {
legend: {
display: true,
position: "bottom"
},
And adding a layput padding so the values dont get outside the canvas.
options: {
layout:{
padding:20
}
},

Several Chart.js canvas in a div but only last one is dispayed

I have several canvas in a page, each displaying a Chart.js chart. I define each chart as:
<div>
<canvas id="chartId1" style="width:100% !important; height: 400px !important;"></canvas>
<canvas id="chartId2" style="width:100% !important; height: 400px !important;"></canvas>
<canvas id="chartIdn" style="width:100% !important; height: 400px !important;"></canvas>
</div>
and populate each in JavaScript (the following code is iterated in a for loop where I pass the canvas id):
var options1 = {
type: 'line',
data: {
labels: [dates],
datasets: [{
label: currentNodeType + ' [ ' + currentNodeUnit + ' ]',
backgroundColor: 'rgb(54, 162, 235, 0.3)',
borderColor: 'rgb(54, 162, 235, 0.3, 0.3)',
data: [values],
pointRadius: 5,
hoverRadius: 6,
borderWidth: 1,
hitRadius: 10
}]
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false,
suggestedMin: 0
}
}]
},
legend: {
display: true,
labels: {
fontSize: 18,
boxWidth: 18
}
},
plugins: {
zoom: {
pan: {
enabled: true
},
zoom: {
enabled: true,
drag: true,
mode: 'xy',
speed: 0.1
}
}
}
}
}
var ctxChart1 = document.getElementById('chartId1').getContext('2d');
var chart1 = new Chart(ctxChart1, options1);
When I open the page in a brwoser only the last canvas is visible and I see empty spaces in place of the others. However when I try to download an image of any invisible chart (I convert it to Base64 as follows) the chart is perfectly fine. Why is it not visible in the page?
var dataURL = chart.toBase64Image();
var a = window.document.createElement('a');
a.href = dataURL;
a.download = fileName + '.png';

How to have onclick/hover display associated value in ChartJS

I have a (regularly updating) ChartJS line chart as follows, working off of three types of data - prices, dates, and associated more_info - collected from a Django API:
<script>
var myChart
function refresh_graph() {
{% block jquery %}
var chart_endpoint = "{% url 'chart_data' current_id %}"
var defaultData = []
var labels = []
var more_info = []
$.ajax({
method: "GET",
url: chart_endpoint,
success: function(data){
defaultData = data.prices
labels = data.dates
more_info = data.more_info
if(myChart){
myChart.destroy();
}
var ctx = document.getElementById('myChart').getContext('2d');
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets : [{
label: 'Price',
data: defaultData,
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 2
}]
},
options: {
elements: {
line: {
tension: 0 // disables bezier curves
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1
}
}]
},
animation: {
duration: 0 // general animation time
},
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsiveAnimationDuration: 0 // animation duration after a resize
}
})
}
})
setTimeout(refresh_graph, 5000);
{% endblock %}
}
setTimeout(refresh_graph, 0);
</script>
<div>
<canvas id="myChart" width="1000" height="400"></canvas>
</div>
I'm trying to figure out how to make it so that, when the user clicks on or hovers over (I'd be happy with either) one of the data points in the graph (i.e., a price at a date), they'll see the associated more_info.
I'm aware of this using getElementById, but can't figure out how to extend that to a case like this, where I'm not looking to display a label (here: date) and a data point value (here: price), but rather a third value, i.e., more_info.
I'm also aware of this way of using custom tooltips, but also can't figure out how to extend this from the case where I'm simply using tooltipItem.xLabel (date) and tooltipItem.yLabel (price), as opposed to a third, associated value.
Here's a solution using tooltips (ignoring the Ajax from the OP):
var myChart
function refresh_graph() {
var labels = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"]
var defaultData = [0.1,0.5,0.3,0.4,0.6,0.8,0.3]
var more_info = ["Monday info", "Tuesday info", "Wednesday info","Thursday info","Friday info","Saturday info","Sunday info"]
if(myChart){
myChart.destroy();
}
var ctx = document.getElementById('myChart').getContext('2d');
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "Price",
data: defaultData,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 2,
}]
},
options: {
responsive : true,
tooltips : {
callbacks : {
title : function() {
return 'More information:';
},
afterLabel : function(tooltipItem, data) {
return 'Information: ' + more_info[tooltipItem.index];
},
}
},
elements: {
line: {
tension: 0
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1
}
}]
},
animation: {
duration: 0
},
hover: {
animationDuration: 0
},
responsiveAnimationDuration: 0
}
})
setTimeout(refresh_graph, 50000);
}
setTimeout(refresh_graph, 0);
Full codepen with custom tooltip here: https://codepen.io/kh_one/pen/OJJPBpJ.

Chart JS — Conditional horizontal row background colours

I'm a bit stuck on adding conditional background colours to a row in ChartJS, based on numbers on the vertical axis.
Eg.
If the vertical axis is between 0 - 6, background colour for those rows is green.
If the vertical axis is between 6 - 12 background colour for those rows is grey
If the vertical axis is > 12 background colour for those rows is red
Has anyone done something like this before?
I've attached a picture that roughly describes the functionality.
Cheers!
There is no option to do this with chartjs. However you can write your own plugin and draw the background by yourself in the beforeDraw hook for example.
var chart = new Chart(ctx, {
plugins: [{
beforeDraw: function(chart) {
//..
}
}]
});
You can get all the information to calculate the height of an y-axis-segment from the chart parameter.
I've included a snippet below how this could be implemented. Note however that this is more a proof of concept than a proper implementation:
var canvas = document.getElementById('myChart');
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var myLineChart = new Chart(canvas,
{
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [
{
label: '# of Votes',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [2, 5, 12.5, 9, 6.3]
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Conditional Background'
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: Infinity
}],
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
},
plugins: [{
beforeDraw: function (chart) {
var ctx = chart.chart.ctx;
var ruleIndex = 0;
var rules = chart.chart.options.backgroundRules;
var yaxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
var partPercentage = 1 / (yaxis.ticksAsNumbers.length - 1);
for (var i = yaxis.ticksAsNumbers.length - 1; i > 0; i--) {
if (yaxis.ticksAsNumbers[i] < rules[ruleIndex].yAxisSegement) {
ctx.fillStyle = rules[ruleIndex].backgroundColor;
ctx.fillRect(xaxis.left, yaxis.top + ((i - 1) * (yaxis.height * partPercentage)), xaxis.width, yaxis.height * partPercentage);
} else {
ruleIndex++;
i++;
}
}
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
Shiffty's answer is right on point, however it only works if the background values are present on the yAxis, which is not always the case... depends on what fits. A more generic solution is to calculate the actual values:
var canvas = document.getElementById('myChart');
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var myLineChart = new Chart(canvas,
{
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [
{
label: '# of Votes',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [2, 5, 12.5, 9, 6.3]
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Conditional Background'
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: 999999
}],
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
},
plugins: [{
beforeDraw: function (chart) {
var rules = chart.chart.options.backgroundRules;
var ctx = chart.chart.ctx;
var yAxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
for (var i = 0; i < rules.length; ++i) {
var yAxisSegement = (rules[i].yAxisSegement > yAxis.ticksAsNumbers[0] ? yAxis.ticksAsNumbers[0] : rules[i].yAxisSegement);
var yAxisPosStart = yAxis.height - ((yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]) + chart.chart.controller.chartArea.top;
var yAxisPosEnd = (i === 0 ? yAxis.height : yAxis.height - ((rules[i - 1].yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]));
ctx.fillStyle = rules[i].backgroundColor;
ctx.fillRect(xaxis.left, yAxisPosStart, xaxis.width, yAxisPosEnd - yAxisPosStart + chart.chart.controller.chartArea.top);
}
}
}]
});

Categories

Resources