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

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

Related

Multiline Chartjs causes issue multiple lines with same data cannot be differentiated

I am displaying a multiline chart using Chartjs.
Many lines here hold same data hence im not able to differentiate them. even if i keep different color for different line i cant see any difference because they all overlap on one another.
At least on hover over the points i want data of all the lines to be shown, but only data on line on the top gets shown. How to understand/see the data in lines behind (first of all how to know which all lines lie behind). (ignore the script error in snippet given below)
var speedCanvas = document.getElementById("speedChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var dataFirst = {
label: "Car A - Speed (mph)",
data: [0, 59, 75, 20, 20, 55, 40],
lineTension: 0,
fill: false,
borderColor: 'red'
};
var dataSecond = {
label: "Car B - Speed (mph)",
data: [0, 59, 75, 20, 20, 55, 40],
lineTension: 0,
fill: false,
borderColor: 'blue'
};
var speedData = {
labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"],
datasets: [dataFirst, dataSecond]
};
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
}
};
var lineChart = new Chart(speedCanvas, {
type: 'line',
data: speedData,
options: chartOptions
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="resources/sources/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<canvas id="speedChart" width="600" height="400"></canvas>
To see all x axes data at once, you can add below configuration in tooltip section
mode: 'index'
and also you can add configuration so that it looks nice like below
intersect: false,
position: 'nearest'
in your case, your options would look something like this
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
},
tooltips:{
mode: 'index',
intersect: false,
position: 'nearest'
}
};

Chart js radar hovercolorbackground not working

I was able to create a great radar chart with Chart js. My only problem is that the datasets attribute hoverBackgroundColor is not making any affect.
Here's my code:
chosen = [[5.2,0,1,9,11],[5.1,2,4,9,7],[5.1,2,2,9,8]]
playerNames= ['Henderson','Baldock','Stevens']
function createRadarComparison(chosen, playerNames) {
var ctx = document.getElementById('myChart').getContext('2d');
var borderColors = ['#ff82827d', '#82ff917d', '#fdff827d','#b882ff7d']
var colors = ['#ff828252', '#82ff8c52', '#fdff8252', '#b882ff52' ];
datasetdata = []
for (var i = 0; i < chosen.length; i++) {
datasetdata[i] = {
label: playerNames[i],
data: chosen[i],
backgroundColor: colors[i],
hoverBackgroundColor: colors[i],
borderColor: borderColors[i],
pointBorderColor: "#fff",
pointBackgroundColor: borderColors[i],
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
}
}
var config = {
type: 'radar',
data: {
labels: ['Price', 'Goals', 'Assits', 'Clean Sheets', 'Bonus'],
datasets: datasetdata
},
options: {
legend: {
position: 'top',
labels: {
"fontSize": 10,
}
},
scale: {
ticks: {
beginAtZero: true,
display: false
}
},
maintainAspectRatio: false,
}
};
var myChart = new Chart(ctx, config);
}
Here's the image of the chart
I am expecting the color of the whole dataset area to change on hover, but nothing changes. Appreciate your help

gradient background on radar chartjs

I've got a radar chartJs.
I cant figure out how to put inside the area a radial gradient.
When putting the current code, it only takes 1 color as background-color by default
current code:
let ctx = document.getElementById('chart-0').getContext("2d");
let gradient = ctx.createLinearGradient(0.000, 150.000, 300.000, 150.000);
// Add colors
gradient.addColorStop(0.035, 'rgba(234, 25, 78, 1.000)');
gradient.addColorStop(0.225, 'rgba(0, 8, 249, 1.000)');
gradient.addColorStop(0.983, 'rgba(42, 255, 0, 1.000)');
let data = {
backgroundColor: gradient,
labels: labelData,
datasets: [{
borderColor: presets.red,
data: [20,20,20,20,20],
label: labeldata
}]
};
const options = {
maintainAspectRatio: true,
spanGaps: false,
scale: {
pointLabels: {
fontSize: 14
}
},
elements: {
line: {
tension: 0.000001
}
},
legend: {
labels: {
fontSize: 16
}
}
};
chart = new Chart('chart-0', {
type: 'radar',
data: data,
options: options
});
Each dataset also should include backgroundColor property with assigned gradient values. I've created JSFiddle based on your code.

Image drawn by drawImage() function hide when mover hover on bar chart column

I draw a chart using chart js on canvas. Then I draw a image on top of the column of chart. When I load the page It shows properly. But when I hover mouse on chart column, image gone hide.
I have tried with chart js. I have tried with morris js.
let myChart = document.getElementById('myChart').getContext('2d');
// Global Options
Chart.defaults.global.defaultFontFamily = 'Lato';
Chart.defaults.global.defaultFontSize = 18;
Chart.defaults.global.defaultFontColor = '#777';
let massPopChart = new Chart(myChart, {
type: 'bar', // bar, horizontalBar, pie, line, doughnut, radar, polarArea
data: {
labels: ['Boston', 'Worcester', 'Springfield', 'Lowell', 'Cambridge', 'New Bedford'],
datasets: [{
label: 'Population',
data: [
6,2,7,3,4,6
],
backgroundColor: '#1d569e',
borderWidth: 1,
borderColor: '#777',
hoverBorderWidth: 3,
hoverBorderColor: '#000'
}]
},
options: {
title: {
display: true,
text: 'Largest Cities In Massachusetts',
fontSize: 25
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#000'
}
},
layout: {
padding: {
left: 50,right: 0,bottom: 0,top: 0
}
},
tooltips: {
enabled: true
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var canvas = document.getElementById('myChart');
var context = canvas.getContext('2d');
var imgPath = 'https://i.imgur.com/t0MRiAf.png';
var imgObj = new Image();
imgObj.src = imgPath;
imgObj.onload = function() {
context.drawImage(imgObj, 0, 0, 100, 100);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div class="container">
<canvas id="myChart"></canvas>
</div>
I want to show the image on top of column. It will be responsive.

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

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>

Categories

Resources