Chart.js is always increasing height on chart.resize() - charts

I added chart.resize() inside of addData and removeData function, but it is always increasing height and it is never decreasing!
I am updating the chart when the user click on item of the menu. Some items have more than 100 datas e some others items have only 2 data and when have few data, the chart is always increasing height:
horizontalBar
Why is this happening?
<canvas id="chart"></canvas>
var chartData = {
labels: [<?php echo '"'.implode('","', $chart_labels ).'"' ?>],
datasets: [
{
data: [<?php echo implode(',', $chart_numbers ) ?>],
backgroundColor: '#184b8f',
hoverBackgroundColor: '#ef3e42'
}
]
};
var barOptions = {
responsive: true,
maintainAspectRatio: false,
tooltips: {
enabled: false
},
hover: {
animationDuration: 0
},
legend: {
display: false
},
scales : {
xAxes : [{
gridLines : {
display: false
},
ticks: {
beginAtZero: true,
color: '#cfcfcf'
}
} ],
yAxes : [ {
gridLines : {
display: false
},
ticks: {
fontSize: 13,
fontFamily: "'Open Sans'",
fontWeight: 600,
}
}]
},
animation: {
duration: 500,
easing: "easeOutQuart",
}
};
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.resize();
chart.update();
}
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.resize();
chart.update();
}
var ctx = document.getElementById("chart").getContext("2d");
var myBar = new Chart(ctx, {
type: 'horizontalBar',
data: chartData,
options: barOptions
});

I had the same thing. You have to put an empty div around the canvas.

I've found some users had the same issue in this post: https://github.com/jtblin/angular-chart.js/issues/84
The solution for me was to change the chart's options to maintainAspectRatio: false.
myChart.setOptions({
responsive: true,
maintainAspectRatio: false
});

In laravel livewire i fixed adding wire:ignore to wrapper div
<div wire:ignore>
<div class="chart-container" style="height: 80vh; width: 80vh;">
<canvas id="bar-chart" height="800" width="1500"></canvas>
</div>
</div>

I was having the same issue in a Bulma tile.
The fix was to set
responsive: false in the Chart.js script options area.

Related

Custom tooltip title based on dictionary mapping of values

MWE: See a graph below with countries in the x-axis. What is the best way to show the whole name in the tooltip instead of the acronym? (Show "Germany" instead of "GER", France instead of "FRA", etc.). I have like 10 or 15 of those.
SEE FULL CODE IN jsfiddle
var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
https://jsfiddle.net/user3507584/6zpb715x/6/
You can add an object with translations where the key is the value from the label and the value is the full country name:
var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
var translations = {
GER: 'Germany',
FRA: 'France',
LT: "Italy"
}
var barChartData2 = {
labels: labels2,
datasets: [{
label: 'Student Count',
backgroundColor: '#ccece6',
data: example2
}]
};
function drawChart(el, data, title) {
var ctx = document.getElementById(el).getContext("2d");
var bar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each bar to be 2px wide and green
elements: {
rectangle: {
borderWidth: 2,
borderColor: '#98c4f9',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'bottom',
},
title: {
display: true,
text: title
},
scales: {
yAxes: [{
ticks: {
beginAtZero: 0,
min: 0
}
}],
xAxes: [{
ticks: {
// Show all labels
autoSkip: false,
callback: function(tick) {
var characterLimit = 20;
if (tick.length >= characterLimit) {
return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';;
}
return tick;
}
}
}]
},
tooltips: {
callbacks: {
title: function(tooltipItem) {
return translations[tooltipItem[0].xLabel];
}
}
}
}
});
console.log(bar);
};
drawChart('canvas0', barChartData2, 'example title');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.js"></script>
<div id="container">
<canvas id="canvas0"></canvas>
</div>

Chart.js ignore options

I'm trying to create a line chart with chart.js but when I try to style my chart.
Everything from options is ignored.
Here is my code:
<canvas id="myChart" width="400" height="400"></canvas>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
let ChartOptions = {
responsive: true,
layout: { padding: { top: 12, left: 12, bottom: 12 } },
title: {
display: true,
text: 'Chart.js Line Chart - Cubic interpolation mode'
},
scales: {
xAxes: [{ gridLines: { color: '#22364e', borderDash: [9, 7] } }],
yAxes: [{ gridLines: { display: false } }]
},
plugins: { datalabels: { display: false } },
legend: { display: false },
elements: {
point: { radius: 5 },
line: { tension: 0.4, fill: false },
},
//tooltips: {},
hover: { mode: 'nearest', animationDuration: 400 },
};
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Fri", "Sun", "Wed", "Thu", "Fri"],
datasets: [
{
fill: false,
borderColor: '#6ebffe',
pointBackgroundColor: '#6ebffe',
pointBorderColor: '#8cff00',
data: [320, 325, 300, 350, 340],
}
],
options: ChartOptions
}
});
</script>
I tried to copy the code from https://www.chartjs.org/samples/latest/charts/line/interpolation-modes.html but it's the same. I can't add options to my chart.
Even the title is not showing. This is not a cache problem because I run it with chrome devtools open and tried with a different browser.
the options are in the wrong place,
they should be placed after the data object
data: {
},
options: ChartOptions
you had them as part of the data object...
data: {
options: ChartOptions
},
see following working snippet...
<canvas id="myChart" width="400" height="400"></canvas>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
let ChartOptions = {
responsive: true,
layout: { padding: { top: 12, left: 12, bottom: 12 } },
title: {
display: true,
text: 'Chart.js Line Chart - Cubic interpolation mode'
},
scales: {
xAxes: [{ gridLines: { color: '#22364e', borderDash: [9, 7] } }],
yAxes: [{ gridLines: { display: false } }]
},
plugins: { datalabels: { display: false } },
legend: { display: false },
elements: {
point: { radius: 5 },
line: { tension: 0.4, fill: false },
},
//tooltips: {},
hover: { mode: 'nearest', animationDuration: 400 },
};
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["Fri", "Sun", "Wed", "Thu", "Fri"],
datasets: [
{
fill: false,
borderColor: '#6ebffe',
pointBackgroundColor: '#6ebffe',
pointBorderColor: '#8cff00',
data: [320, 325, 300, 350, 340],
}
]
},
options: ChartOptions
});
</script>

How to properly use the chartjs datalabels plugin

I'm using Chart.js to create a bar char, I have to display the percentage on each bar, so I found the chartjs-plugin-datalabels, but I can't make it work, the documentation and the examples are not clear for me.
This is What I got:
HTML:
<canvas id="bar-chart" width="800" height="450"></canvas>
Javascript:
// Bar chart
var valuedata= [2478,5267,734,784,433];
var valuelabel=["Africa", "Asia", "Europe", "Latin America", "North America"];
var myBarChart = new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: valuelabel,
datasets: [
{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: valuedata,
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
},
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false,
drawBorder: false
},
ticks: {
display: false
}
}]
},
plugins: {
datalabels: {
color: 'white',
display: function(context) {
console.log("Algo: "+context);
return context.dataset.data[context.dataIndex] > 15;
},
font: {
weight: 'bold'
},
formatter: function(value, context) {
return context.dataIndex + ': ' + Math.round(value*100) + '%';
}
}
}
}
});
myBarChart.update();
Supposedly, from what I get, the "plugin" inside option is the one that let the values to be display, but as I shown in my code above, doesn't work for me, surely I'm missing something but I don't know what, can somebody help me?
Thanks.
Fiddle:
https://jsfiddle.net/s64bq4sw/16/
It was because of the version of the Chartjs I was using, this plugin requieres 2.7.0 or later.

ChartJS - ignore labels

I am using ChartJS and need a chart like this: https://tppr.me/OE08p
Meaning it should ignore 4 of the labels (flexibility, external, stability, internal) and connect the dots from the other 4 labels (like the red lines show on the screenshot).
Can I ignore these 4 labels data-wise somehow, but keep them?
Other chart packages/solutions are welcome, if it is not possible in chartjs.
You can use highchart.js library, see:
docs: https://www.highcharts.com/docs/chart-and-series-types/polar-chart
example: https://www.highcharts.com/demo/polar-spider
with these options:
plotOptions: {
series: {
connectNulls: true
}
}
and filtering data with map function like below (just for example):
data.map(filter)
<omissis>
function filter(item, index) {
if (index==2)
return null;
else
return item;
}
here is a jsfiddle showing this approach: http://jsfiddle.net/beaver71/w6ozog1c/
or a snippet here:
// original data
var data1 = [43000, 19000, 60000, 35000, 17000, 10000],
data2 = [50000, 39000, 42000, 31000, 26000, 14000];
var chart = Highcharts.chart('container', {
chart: {
polar: true,
type: 'line'
},
title: {
text: 'Budget vs spending',
x: -80
},
pane: {
size: '80%'
},
xAxis: {
categories: ['Sales', 'Marketing', 'Development', 'Customer Support',
'Information Technology', 'Administration'],
tickmarkPlacement: 'on',
lineWidth: 0
},
yAxis: {
gridLineInterpolation: 'polygon',
lineWidth: 0,
min: 0
},
tooltip: {
shared: true,
pointFormat: '<span style="color:{series.color}">{series.name}: <b>${point.y:,.0f}</b><br/>'
},
legend: {
align: 'right',
verticalAlign: 'top',
y: 70,
layout: 'vertical'
},
series: [{
name: 'Allocated Budget',
data: data1.map(filter), // filtered data
pointPlacement: 'on',
color: 'red'
}, {
name: 'Actual Spending',
data: data2,
pointPlacement: 'on',
color: 'green'
}],
plotOptions: {
series: {
lineWidth: 2,
connectNulls: true // connects also null value (bypassing)
}
}
});
var filterOn = true;
$('#button').click(function () {
filterOn = !filterOn;
if (filterOn)
chart.series[0].setData(data1.map(filter));
else
chart.series[0].setData(data1);
});
// filter function with your criteria
function filter(item, index) {
if (index==2)
return null;
else
return item;
}
.highcharts-grid-line {
stroke-width: 2;
}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<button id="button">Toggle filter (ignoring a point in red serie)</button>
<div id="container" style="min-width: 400px; max-width: 600px; height: 400px; margin: 0 auto"></div>

In Chart.js set chart title, name of x axis and y axis?

Does Chart.js (documentation) have option for datasets to set name (title) of chart (e.g. Temperature in my City), name of x axis (e.g. Days) and name of y axis (e.g. Temperature). Or I should solve this with css?
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [data]
}
]
}
Realy thanks for help.
In Chart.js version 2.0, it is possible to set labels for axes:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See Labelling documentation for more details.
For Chart.js version 3
options = {
scales: {
y: {
title: {
display: true,
text: 'Your Title'
}
}
}
}
If you have already set labels for your axis like how #andyhasit and #Marcus mentioned, and would like to change it at a later time, then you can try this:
chart.options.scales.yAxes[ 0 ].scaleLabel.labelString = "New Label";
Full config for reference:
var chartConfig = {
type: 'line',
data: {
datasets: [ {
label: 'DefaultLabel',
backgroundColor: '#ff0000',
borderColor: '#ff0000',
fill: false,
data: [],
} ]
},
options: {
responsive: true,
scales: {
xAxes: [ {
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
} ],
yAxes: [ {
display: true,
scaleLabel: {
display: true,
labelString: 'value'
}
} ]
}
}
};
For Readers in 2021:
Version
"chart.js": "^3.3.2",
Real World Working Sample:
const optionsTemplate = (yAxisTitle, xAxisTitle) => {
return {
scales: {
yAxes: {
title: {
display: true,
text: yAxisTitle,
font: {
size: 15
}
},
ticks: {
precision: 0
}
},
xAxes: {
title: {
display: true,
text: xAxisTitle,
font: {
size: 15
}
}
}
},
plugins: {
legend: {
display: false,
}
}
}
}
In chart JS 3.5.x, it seems to me the title of axes shall be set as follows (example for x axis, title = 'seconds'):
options: {
scales: {x: { title: { display: true, text: 'seconds' }}}
}
see: https://www.chartjs.org/docs/latest/axes/labelling.html
just use this:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["1","2","3","4","5","6","7","8","9","10","11",],
datasets: [{
label: 'YOUR LABEL',
backgroundColor: [
"#566573",
"#99a3a4",
"#dc7633",
"#f5b041",
"#f7dc6f",
"#82e0aa",
"#73c6b6",
"#5dade2",
"#a569bd",
"#ec7063",
"#a5754a"
],
data: [12, 19, 3, 17, 28, 24, 7, 2,4,14,6],
},]
},
//HERE COMES THE AXIS Y LABEL
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
});
</script>
If you are using chart JS v4 try this.
options = {
scales: {
y: {
title: {
display: true,
text: 'Test'
}
},
x: {
title: {
display: true,
text: 'Test'
}
}
},
plugins: {
legend: {
display: false,
},
}
}
<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
See example with name of x axis and y axis left and right.
public barChartOptions: ChartOptions = {
title: {
display: true,
text: 'Custom Chart Title',
},
responsive: true,
legend: {
position: 'right',
},
scales: {
yAxes: [
{
position: 'right',
scaleLabel: {
display: true,
labelString: 'Frequency Rate - right',
},
},
{
position: 'left',
scaleLabel: {
display: true,
labelString: 'Frequency Rate - left',
},
},
],
xAxes: [
{
display: true,
position: 'bottom',
scaleLabel: {
display: true,
labelString: 'Titulo do eixo X',
fontStyle: 'italic',
fontSize: 12,
fontColor: '#030',
},
},
],
},
};