Resizing a Chart.js chart - javascript

The Chart Spans across the entire Web Page and I cant resize it. I've tried seting the height/width of the canvas and the canvas with no luck.
Here is my Html:
<div id="chartbox">
<canvas id="myChart" display="block"></canvas>
</div>
<script>
var xaxis = [1,2,3,4,5]
var yaxis = [2,3,4,5,6]
var thisChart = new Chart(document.getElementById("myChart"), {
type: 'line',
options: {
responsive: true
},
data: {
labels: xaxis,
datasets: [
{
data: yaxis,
label: "Test",
borderColor: "#3e95cd",
}
]
}
});
</script>

If you are styling the canvas element directly with non relative values you need to set responsive to false in the options, if you are styling the width with relative values you need to apply them to the surrounding div
https://www.chartjs.org/docs/master/configuration/responsive.html

I hope my answer is helpful to you, you just have to specify certain CSS rules for the parent element of the graphic.
var xaxis = [1,2,3,4,5]
var yaxis = [2,3,4,5,6]
var thisChart = new Chart(document.getElementById("myChart"), {
type: 'line',
options: {
responsive: true
},
data: {
labels: xaxis,
datasets: [
{
data: yaxis,
label: "Test",
borderColor: "#3e95cd",
}
]
}
});
#chartbox {
display: block;
width: 400px;
height: 400px;
}
<div id="chartbox">
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Related

Chart.js identification of min and max value before rendering

I am using chart.js for my project. As you can see in the following code, chart.js uses different minimum and maximum values for y-axis for line and bar graphs for same data. In the given code, 1100-1700 is the value range for line graph whereas 0-2000 is the value range used for bar graph.
I like to make same minimum and maximum values for both line and bar graphs. One option is to find minimum, maximum and step-size values my own and use the properties min, max and ticks.stepSize under scales. But finding minimum, maximum and step-size for a given data data is a serious task.
For my requirement, default minimum ,maximum and stepSize used by chart.js for line graph is fine and I would like to use the same values for bar graph also.
I could first render line graph, get these values from this graph (like scales.y.min) and then use it for bar graph, which is perfectly working
Is there a way I could get the default min, max, stepSize values used by chart.js for line graph before actually drawing the graph? Any answers or pointers are really appreciated. Thanks
var chart1 = new Chart(document.getElementById('chart1'),
{
type: 'line',
data:
{
labels: ['a','b','c'],
datasets:
[
{
label: 'A',
data: [1212,1122, 1188, 1617, 1116],
borderColor: 'green',
}
]
}
});
var chart2 = new Chart(document.getElementById('chart2'),
{
type: 'bar',
data:
{
labels: ['a','b','c'],
datasets:
[
{
label: 'A',
data: [1212,1122, 1188, 1617, 1116],
backgroundColor: 'green',
}
]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<div style="width:300px;height:200px"><canvas id="chart1"></canvas></div>
<div style="width:300px;height:200px"><canvas id="chart2"></canvas></div>
The first thing you could do is to set beginAtZero to false to Y axis of bar chart because is set to true by default:
https://github.com/chartjs/Chart.js/blob/v3.9.1/src/controllers/controller.bar.js#L636-L650
Then you can set the same scale config to both charts.
options: { // options of charts
scales: {
y: {
beginAtZero: false,
}
}
}
var chart1 = new Chart(document.getElementById('myChart1'),
{
type: 'line',
data:
{
labels: ['a','b','c'],
datasets:
[
{
label: 'A',
data: [1212,1122, 1188, 1617, 1116],
borderColor: 'green',
}
]
},
options: {
scales: {
y: {
beginAtZero: false,
}
}
}
});
var chart2 = new Chart(document.getElementById('myChart2'),
{
type: 'bar',
data:
{
labels: ['a','b','c'],
datasets:
[
{
label: 'A',
data: [1212,1122, 1188, 1617, 1116],
backgroundColor: 'green',
}
]
},
options: {
scales: {
y: {
beginAtZero: false,
}
}
}
});
.myChartDiv {
max-width: 300px;
max-height: 200px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart1" width="300" height="200"/>
</div>
<div class="myChartDiv">
<canvas id="myChart2" width="300" height="200"/>
</div>
</body>
</html>

Chart JS tick options not working for y axis

I have been struggling to make a chart.js line chart start at 0 when all of the values are 0. If all of the data of a dataset is 0 the y axis will always show values below 0 which I don't want there.
Here is the example:
<div class="container">
<canvas id="lineChart"></canvas>
<script>
var ctx = document.getElementById('lineChart');
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: [1,2,3],
datasets: [{
data: [0, 0, 0]
}]
},
options: {
responsive: true,
scales: {
y: {
ticks: {
beginAtZero:true
}
}
}
}
});
</script>
<div>
As you can see I am changing the options the scales as suggested in the documentation here (apparently there has been migration and this is the way to go in v3, which is what I am using). But the graph still won't start at 0:
Any axis options other than the ticks work correctly.
Any ideas of what I might be doing wrong?
You tried to place the beginAtZero in the V2 place, in V3 you have to put it in the root of the scale object like so:
const options = {
type: 'line',
data: {
labels: [1, 2, 3],
datasets: [{
label: '# of Votes',
data: [0, 0, 0],
borderColor: 'pink'
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
}
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>
For all changes between V2 and V3 you can read the migration guide

How to show slice value inside of slice in pie chart using chart.js

I am having an scenario, where I need to show the slice value inside of the slice in pie chart. I am having more than 1 pie charts on my webpage. Below code is perfectly working but only for 1st Pie Chart and for others its throwing error as below, could you please help me to sort this out?
Error:: unCaught TypeError: cannot read the property 'data' of undefined.
Code::
options:{
animation:{
onComplete:function(){
var ctx = this.chart.ctx;
var dataset_obj = this.data.datasets;
for (var i=0;i<dataset_obj.length; i++){
var meta_obj = dataset_obj[i]._meta[i].data;
for (var j=0; j<meta_obj.length; j++){
var model =meta_obj[j]._model;
start_angle= model.startAngle;
end_angle = model.endAngle;
mid_angle =start_angle + ( end_angle -start_angle)/2;
mid_radius = model.innerRadius + (model.outerRadius -model.innerRadius)/2;
var x =mid_radius*math.cos(mid_angle);
var y = mid_radius*math.cos(mid_angle);
ctx.fillstyle='#fff';
if (dataset_obj[i].data[j] != 0 && meta_obj[j].hidden != true){
ctx.fillText(dataset_obj[i].data[j], model.x+x, model.y+y);
}
}
}
}
}
}
This answers the issue contained in the question's title:
How to show slice value inside of slice in pie chart using chart.js
The code snippet below show how to display the values inside the slices with the use of chartjs-plugin-labels. The code of the samples was extracted from the chartjs-plugin-labels demo page.
var canvas = document.getElementById('myChart');
new Chart(canvas, {
type: 'pie',
data: {
labels: ['January', 'February', 'March'],
datasets: [{
data: [50445, 33655, 15900],
backgroundColor: ['#FF6384', '#36A2EB','#FFCE56']
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
labels: {
render: 'value',
fontColor: ['green', 'white', 'red']
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<canvas id="myChart"></canvas>
If you want to display the percentage of each slice, you can do the following:
var canvas = document.getElementById('myChart');
new Chart(canvas, {
type: 'pie',
data: {
labels: ['January', 'February', 'March'],
datasets: [{
data: [50445, 33655, 15900],
backgroundColor: ['#FF6384', '#36A2EB','#FFCE56']
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
labels: {
render: 'percentage',
fontColor: ['green', 'white', 'red'],
precision: 2
}
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<canvas id="myChart"></canvas>

Chart.js: width and height of a pie chart not respected

I'm using Chart.js to create pie charts. I need each chart to be 76x76px. Unfortunately, the rendered chart is always a bit smaller than the size if the wrapping div and the canvas itself.
If you inspect the chart in the FIDDLE, you'll see what I mean: the canvas element has a fixed size but the chart itself doesn't fill it fully.
It's almost as if there was a top margin reserved for something that isn't there.
The code:
HTML
<div class="wrapper">
<canvas id="myChart" width="76" height="76"></canvas>
</div>
JS
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: [{
data: [30, 70],
backgroundColor: [
'green',
'gray'
],
borderWidth: 0
}]
},
options: {
tooltips: {
enabled: false
},
events: []
}
});
CSS
.wrapper {
width: 76px;
height: 76px;
}
Any ideas what I should do to make the pie chart fill the 76x76px canvas?
The additional space is reserved for the legend, which is enabled by default. Simply disable it and you should have the whole space for the chart:
legend: {
display: false
}
A working example:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: [{
data: [30, 70],
backgroundColor: [
'green',
'gray'
],
borderWidth: 0
}]
},
options: {
tooltips: {
enabled: false
},
legend: {
display: false // <- the important part
},
events: []
}
});
.wrapper {
width: 76px;
height: 76px;
border: 1px solid black; /* for demonstration purposes*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js" integrity="sha512-d9xgZrVZpmmQlfonhQUvTR7lMPtO7NkZMkA0ABN3PHCbKA5nqylQ/yWlFAyY6hYgdF1Qh6nYiuADWwKB4C2WSw==" crossorigin="anonymous"></script>
<div class="wrapper">
<canvas id="myChart" width="76" height="76"></canvas>
</div>

Make Chart.js horizontal bar labels multi-line

Just wondering if there is any way to set the horizontal bar labels for y-axis using chart.js. Here is how I set up the chart:
<div class="box-body">
<canvas id="chart" style="position: relative; height: 300px;"></canvas>
</div>
Javascript:
var ctx = document.getElementById('chart').getContext("2d");
var options = {
layout: {
padding: {
top: 5,
}
},
responsive: true,
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: {
labels: label,
datasets: [{
data: price,
}]
},
options: options
};
if (chart) chart.destroy();
chart= new Chart(ctx, opt);
chart.update();
As you all can see, the first and third labels are too long and cut off. Is there a way to make the label multi-line?
If you want to have full control over how long labels are broken down across lines you can specify the breaking point by providing labels in a nested array. For example:
var chart = new Chart(ctx, {
...
data: {
labels: [["Label1 Line1:","Label1 Line2"],["Label2 Line1","Label2 Line2"]],
datasets: [{
...
});
You can use the following chart plugin :
plugins: [{
beforeInit: function(chart) {
chart.data.labels.forEach(function(e, i, a) {
if (/\n/.test(e)) {
a[i] = e.split(/\n/);
}
});
}
}]
add this followed by your chart options
ᴜꜱᴀɢᴇ :
add a new line character (\n) to your label, wherever you wish to add a line break.
ᴅᴇᴍᴏ
var chart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['Jan\n2017', 'Feb', 'Mar', 'Apr'],
datasets: [{
label: 'BAR',
data: [1, 2, 3, 4],
backgroundColor: 'rgba(0, 119, 290, 0.7)'
}]
},
options: {
scales: {
xAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
plugins: [{
beforeInit: function(chart) {
chart.data.labels.forEach(function(e, i, a) {
if (/\n/.test(e)) {
a[i] = e.split(/\n/);
}
});
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Categories