How to get chart size (without labels) with chart.js? - chart.js

Now i have this chart:
https://codepen.io/UnluckySerivelha/pen/BawpPYv
const ctx = document.getElementById('graph').getContext('2d');
var bar_ctx = document.getElementById('graph').getContext('2d');
x=["14 Dec","15 Dec"];
y1={"14 Dec":0,"15 Dec":0,};
y2={"14 Dec":0,"15 Dec":0,};
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: x,
datasets: [
{
label: 'Всего за день',
data: y1
},
{
label: 'Будет начислено по вкладам',
data: y2,
},
]
},
options: {
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value, index, values) {
return '$ ' + value;
}
}
}
},
responsive: true,
maintainAspectRatio: false
},
});
I want to add background image for chart area, but not for labels. I know how to add background image, but don't know how to get size of chart area without labels for assignment size and position of image. Is it possible?

You can check the chartArea property that is available in the chart context. This property has the width and height of the area where the chart itself is being drawn.
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
console.log('height: ', chart.chartArea.height);
console.log('width: ', chart.chartArea.width)
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>
Your own code with the background colored pink: https://codepen.io/leelenaleee/pen/OJxWoPe
Official example on using an image as background: https://www.chartjs.org/docs/master/configuration/canvas-background.html#image

Related

Can I make Y axis begin at specific value in ChartJS?

I have this chart, starting at 0 and I want the Y axis to begin at 20. It surprises me how there is nothing related to this in the official ChartJS docs. Is this possible in any way?
I have tried several ways to do it, eg. with ticks or min value and so on but nothing worked.
The application is written in Nuxt3 and the ChartJS library used is vue-chart-3.
const options = computed(() => ({
responsive: true,
plugins: {
legend: {
display: false,
},
title: {
display: false,
}
},
scales: {
x: {
stacked: true,
},
y: {
stacked: true,
}
}
}));
const chartData = computed(() => ({
labels: ['Provider'],
datasets: [
{
data: [selectedDataset.value?.score.uncustomized],
backgroundColor: ['#00b7c4'],
},
{
data: [selectedDataset.value?.score.difference],
backgroundColor: ['#204992'],
},
],
}));
const { barChartProps, barChartRef } = useBarChart({
chartData,
options,
});
Any help would be appreciated.
If you want the axis to start at a given number you need to use the min property:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
scales: {
y: {
min: 6
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

Show center tick value radar chart- Chart.js

I have a radar chart and I'd like to display the value for the tick at the center of the chart over the center. My r scale is set up as follows, and my data is an integer ranging from 1-5.
scales: {
r: {
min: 1,
max: 5,
ticks: {
stepSize: 1,
z: 10,
},
},
},
Over the center of the radar chart, I'd like the tick value displayed, like it's displayed for all other values. Setting my min to 0 (one step size lower than my actual min) displays my ticks, but I'd like the center of my graph to be labeled instead of having a minimum size between the center and the first tick.
You will need to use a custom plugin to draw it on the canvas yourself like so:
const options = {
type: 'radar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
plugins: {
centerTick: {
//color: 'grey' // Set custom color for y
}
}
},
plugins: [{
id: 'centerTick',
afterDraw: (chart, args, opts) => {
const {
ctx
} = chart;
ctx.fillStyle = opts.color || Chart.defaults.color;
ctx.fillText(chart.scales.r.min, chart.scales.r.xCenter - (ctx.measureText(chart.scales.r.min).width / 2), chart.scales.r.yCenter)
}
}]
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

How to change font size, padding of chart title only, in chart.js 3.x

I am trying to reduce padding and increase title text font size , I went though few example but dont seem to work. Even on placing the parameter at multiple places.
const labels1_1 = ['1','2','3', '4', '5','6','7', '8','9+'];
const data1_1 = {
labels: labels1_1,
datasets: [{
label: 'Trucks',
data: [1,2,3, 4, 5,6,7, 8,9],
backgroundColor: '#4472C4',
borderColor: '#4472C4',
borderWidth: 1
}]
};
const config1_1 = {
type: 'bar',
data: data1_1,
options: {
title:{
padding:5,
fontSize:18
},
plugins: {
title: {
display: true,
text: 'Number of SS vs Number of Trucks',
padding:5,
fontSize:18
},
datalabels: {
align: 'end',
anchor: 'end',
backgroundColor: '#3472C4'
},
},
scales: {
y: {
display:true,
beginAtZero: true,
title: {
display: true,
text: 'SS'
}
},
}
},
};
const myChart1_1 = new Chart(
document.getElementById('myChart1_1'), config1_1);
I went through https://www.chartjs.org/docs/2.8.0/configuration/title.html but didnt help. Also how to mention it globally so all titles have bigger font. text: 'Number of SS vs Number of Trucks' is the title.
The Title options have evolved quite a bit in v2 of Chartjs. I found that the title was hidden entirely until I added padding - for one example
options: {
plugins: {
title: {
display: true,
text: "Title" ,
padding: {
top: 10,
bottom: 10
},
font: {
size: 24,
style: 'italic',
family: 'Helvetica Neue'
}
}
},
... other options here
}
The reason it didn't help is because you are looking at the docs for version 2.8.0 as you can see in the url, the latest version is 3.6.2 and has some breaking changes against v2.
To adjust the font propertys you will need to define them in the font object in the title config like so:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
plugins: {
title: {
display: true,
text: 'Number of SS vs Number of Trucks',
font: {
size: 30
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>
latest V3 documentation: https://www.chartjs.org/docs/latest/

Legend on chart.js

I'm trying to make a legend with a perfect box, but I don't know how, the "Nível Op. Max" is not like the others,I think the reason this happens is because it's a dotted line and the others are solid lines.
Does anyone know if there is any property in chart.js that causes the square's edge to not be dotted?
My code:
legend: {
display: true,
labels: {
fontSize: 10,
boxWidth: 10
}
The way I want:
You can provide a custom generateLabels function and dont provide the setting for making the border dashed like so:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange',
borderDash: [2, 2]
}
]
},
options: {
plugins: {
legend: {
labels: {
generateLabels: (chart) => {
const datasets = chart.data.datasets;
const {
labels: {
usePointStyle,
pointStyle,
textAlign,
color
}
} = chart.legend.options;
return chart._getSortedDatasetMetas().map((meta) => {
const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
const borderWidth = Chart.helpers.toPadding(style.borderWidth);
return {
text: datasets[meta.index].label,
fillStyle: style.backgroundColor,
fontColor: color,
hidden: !meta.visible,
lineCap: style.borderCapStyle,
lineDashOffset: style.borderDashOffset,
lineJoin: style.borderJoinStyle,
lineWidth: (borderWidth.width + borderWidth.height) / 4,
strokeStyle: style.borderColor,
pointStyle: pointStyle || style.pointStyle,
rotation: style.rotation,
textAlign: textAlign || style.textAlign,
borderRadius: 0,
datasetIndex: meta.index
};
})
}
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.js"></script>
</body>

Chartjs - display radarchart lines from center to corner value

Is there a way to achieve for radarchart from chartjs to display line from center (value 0) to value of the corner? It would looks something like this:
radarchart_image
This is possible by writing a custom inline plugin like so:
var options = {
type: 'radar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
plugins: {
customLine: {
//specify line color
lineColor: 'red'
}
}
},
plugins: [{
id: 'customLine',
afterDatasetDraw: (chart, args, options) => {
const {
ctx,
chartArea
} = chart;
const {
meta
} = args;
// only do the first dataset lines, if you remove this if it will draw lines for all datasets
if (meta.index > 0) {
return;
}
meta.data.forEach((dataPoint) => {
//default line color black as fallback if no color is specified
ctx.strokeStyle = options.lineColor || 'black';
ctx.beginPath();
ctx.moveTo(chartArea.width / 2, chartArea.height / 2 + chartArea.top);
ctx.lineTo(dataPoint.x, dataPoint.y);
ctx.stroke();
})
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.0/chart.js" integrity="sha512-LlFvdZpYhQdASf4aZfSpmyHD6+waYVfJRwfJrBgki7/Uh+TXMLFYcKMRim65+o3lFsfk20vrK9sJDute7BUAUw==" crossorigin="anonymous"></script>
</body>