vue3 chart-js showing previous data on hover - javascript

vue3 chart-js showing previous data on hover.
I updated my chart data filed using API data but after updating the chat data, chart is showing previous API data on hover
i also tried using distory()
here are my codes
methods: {
barChart() {
var Chart = require("chart.js");
let options = new Chart(document.getElementById("bar-chart-grouped"), {
type: "bar",
data: {
labels: this.llabels,
datasets: [
{
label: "पुरुष जनसंख्या",
backgroundColor: "rgba(0, 143, 251, 0.8)",
data: this.mdata,
},
{
label: "महिला जनसंख्या",
backgroundColor: "rgba(0, 227, 150, 0.8)",
data: this.Fdata,
},
{
label: "पअन्य जनसंख्या",
backgroundColor: "rgb(254, 176, 25,0.8)",
data: this.Odata,
},
],
},
});
if (!this.chart) {
this.chart = options;
} else {
this.chart.options = options;
this.chart.update();
}
},
}

Instead of this.chart.options = options;, use this.chart.options = options.options;
The variable options is holding your chart, not only the options.
A better approach would be to only create the chart on the first run of that method (=> place the new Chart inside the if)

Related

charts js, doughnut chart not rendering tooptips correctly

i have a multilevel donut chart but it is not rendering correctly here is code
the problem is, onmouseover on all green parts it says objects, on all grey parts it says products, solution i would like is, on outer ring it should say products, in middle objects, and inner most should be materials, grey areas should just show number. here is a jsfiddle of the problem
Code:
var op=93;
var ap=99;
var mp=66;
var ctx = new Chart(myChart, {
type: 'doughnut',
data: {
labels: ['Objects', 'Products', 'Materials'],
datasets: [{
label: 'Objects',
data: [op, 100 - op],
backgroundColor: ['#006a4e','#eeeeee'],
hoverOffset: 4
},{
label: 'Products',
data: [ap, 100 - ap],
backgroundColor: ['#2e856e', '#eeeeee'],
hoverOffset: 4
},
{
label: 'Materials',
data: [mp, 100 - mp],
backgroundColor: ['#5ca08e', '#eeeeee'],
hoverOffset: 4
}
]
},
options: {
//cutoutPercentage: 40,
height: 200,
width:200
}
});
You can achieve that fairly simple with Chart.JS 2.7.2. Add labels to each dataset like this:
data: {
labels: ['Existing', 'Non'],
datasets: [
{
labels: ['Objects', 'Non-objects'],
...
}, {
labels: ['Products', 'Non-products'],
...
},
{
labels: ['Materials', 'Non-materials'],
...
}
]
}
And add the following label tooltip callback:
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
}
}
}
Demo: https://jsfiddle.net/adelriosantiago/fxd6vops/3/
I am sure it is possible with Chart.JS > 3.0 too but I have no idea how since quite a few things changed in the structure.
I had a same problem which took a lot of time but what worked in the end was importing these elements and initialising them ..
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
ChartJS.register(ArcElement, Tooltip, Legend);
these are the elements that helps make the entire chart. you can't skip them

Uncaught type error: mychart.update is not a function

I am building external buttons to toggle the visibility of data from chartjs, but it will only works when the screen size changed. So, I found that can use mychart.update() to solve the problem. But it get me the error that I stated in the title.
Here is my chart:
var myRadarChart = {
type: 'radar',
data: {
labels: lbl,
datasets: [
{
label: 'Houses',
data: yh,
backgroundColor:['rgba(0, 123, 255, 0.5)'],
borderColor: ['rgba(0, 123, 255, 0.8)'],
hidden:false
},
{
label: 'Apartments',
data: ya,
backgroundColor:['rgba(40,167,69, 0.5)'],
borderColor: ['rgba(40,167,69, 0.8)'],
hidden:false
},
{
label: 'Rooms',
data: yr,
backgroundColor:['rgba(218, 17, 61,0.5)'],
borderColor: ['rgba(218,17,61,0.8)'],
hidden:false
}
]
},
options: {
legend:{
display:true,
onHover: function(event, legendItem) {
document.getElementById("myRadarChart").style.cursor = 'pointer';},
},
maintainAspectRatio:false,
scale: {
angleLines: {
display: true
},
ticks: {
suggestedMin: 0,
suggestedMax: 0
}
}
}
};
var ctx = document.getElementById('myRadarChart').getContext('2d');
new Chart(ctx, myRadarChart);
And how I trying to do is:
//Onclick
function getData(dontHide){
switch(dontHide){
case 0:
myRadarChart.data.datasets[0].hidden=false;
myRadarChart.data.datasets[1].hidden=true;
myRadarChart.data.datasets[2].hidden=true;
myRadarChart.update();
break;
case 1:
myRadarChart.data.datasets[0].hidden=true;
myRadarChart.data.datasets[1].hidden=false;
myRadarChart.data.datasets[2].hidden=true;
myRadarChart.update();
break;
case 2:
myRadarChart.data.datasets[0].hidden=true;
myRadarChart.data.datasets[1].hidden=true;
myRadarChart.data.datasets[2].hidden=false;
myRadarChart.update();
break;
}
}
Or is there alternative ways to perform something like this?
Your issue is that you're trying to call the .update() method on your graph's config object, not your actual graph instance. As you can see, myRadarChart is just an object, it doesn't have a method called update() on it. However, the graph you create when doing new Chart(ctx, myRadarChart); does give you the .update() method.
To fix your issue, you'll need to first store the instance of your graph somewhere:
var radarGraph = new Chart(ctx, myRadarChart);
Then update the graph's data (rather than your config object directly):
radarGraph.data.datasets[0].hidden = false;
...
Then call the update method on your radarGraph object:
radarGraph.update();

How to expand the slice of donut chart in chartjs?

Is there any way to expand the slice of donut chart onclick event or mouse hover in chartjs ?.
I am using chart.js#2.8.0 version.
I have fixed this issue using the following code:
let segment;
this.chart = new Chart(this.canvas, {
type: this.type,
data: this.data,
options: {
...this.options,
onHover: function (evt, elements) {
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 10;
} else {
if (segment) {
segment._model.outerRadius -= 10;
}
segment = null;
}
},
layout: {
padding: 30
}
}
});
I hope it helps you.
Shift-zooming the currently selected slice is not a feature but it has been discussed several times on various forums and the project's GitHub community:
https://forum.mendixcloud.com/link/questions/85582
https://github.com/chartjs/Chart.js/issues/1451
The Github discussion contains a fiddle someone wrote for a Pie chart with Chart.js 1.0. Here is an updated version for the current Chart.js version that supports Donut charts.
Code:
This part only shows the part that zooms the active element, it is just to give you the idea of how to use the active elements .innerRadius and .outerRadius properties to shift the element. The fiddle contains the complete code that also handles shrinking the previously selected element.
<div style="width:400px;">
<canvas id="myChart" width="200" height="200"></canvas>
</div>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'doughnut',
options: {
layout: {
padding: 30
}
},
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [
{
label: '# of Votes',
data: [4, 5, 3],
backgroundColor: [
'rgba(255, 0, 0, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 3
}]
}
});
var addRadiusMargin = 10;
$('#myChart').on('click', function(event) {
var activePoints = myChart.getElementsAtEvent(event);
if (activePoints.length > 0) {
// update the newly selected piece
activePoints[0]['_model'].innerRadius = activePoints[0]['_model'].innerRadius +
addRadiusMargin;
activePoints[0]['_model'].outerRadius = activePoints[0]['_model'].outerRadius +
addRadiusMargin;
}
myChart.render(300, false);
}
Sample image:
Here is a sample of the highlighted slice:
Limitations:
There are two limitations of the sample that I haven't included:
Chart.js does not allow to define a margin between legend and chart content so when you are "zooming"/"moving", the zoomed slice might overlap parts of the legend. You may solve this by extending the legend as shown in Jordan Willis' Codepen which was the result of this SO question.
The selected slice will stay in contact with the remaining slices. If you want it to have a gap, you need to translate x and y of the active slice based on the .startAngle and .endAngleproperties of the active slice.
Another simple trick : hoverBorderWidth
var ctx = document.getElementById("chart").getContext('2d');
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Microsoft Internet Explorer", "Google Chrome", "Mozilla Firefox", "Opera", "Safari"],
datasets: [{
label: 'Number of votes',
data: [60, 20, 10, 8, 5],
backgroundColor: ['#96ceff', '#424348', '#91ee7c', '#f7a35b', '#8286e9'],
borderColor: '#fff',
borderWidth: 1,
hoverBorderColor: ['#96ceff', '#424348', '#91ee7c', '#f7a35b', '#8286e9'],
hoverBorderWidth: 8
}]
},
options: {
responsive: false,
legend: {
display: false
},
tooltips: {
displayColors: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chart" width="350" height="350"></canvas>

Polar Area onclick event

I have following polar Area chart
bellow is the code
var dataset = {
datasets: [{
data: [Above30total, D21toD30total, D11toD20total,D0toD10total],
backgroundColor: [
"rgba(247, 13, 26,0.6)",
"rgba(255, 128, 64,0.6)",
"rgba(65, 163, 23,0.6)",
"rgba(52, 45, 126,0.6)"
],
label: 'My dataset' // for legend
}],
labels: ["ABOVE 30","21 - 30","11 - 20","0 - 10"]
};
var ctx = $("#myChart");
new Chart(ctx, {
data: dataset,
type: 'polarArea'
}
});
what I want is when I click on data shown are for example purple or if I click on green I want to get the data of that clicked area.
for example, if I click on purple I want to get the count of purple.
I have used below code but it is click method for the entire graph not for the data area.
$("#myChart").click(function (evt) {
console.log(evt);
});
any idea how to archive this
after mush research i found the answer
var ctx = $("#myChart");
new Chart(ctx, {
data: dataset,
type: 'polarArea',
options: {
'onClick' : function (evt, data) {
}
}
}
});

Chartjs cannot read property datasets of undefined

I'm developing a React app and trying to get Chartjs to work having imported it from its npm package. The following is the initialization code:
//in my constructor
this.usageChart = null;
//in componentDidMount
let chartContext = document.getElementById("proc_usage");
let initialDataIdle = [100, 100, 100, 100, 100, 100, 100, 100, 100, 100];
let initialDataOther = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
console.log("Creating chart");
this.usageChart = new Chart(chartContext, {
type: "line",
data: {
datasets: [
{ label: "User", fill: true, data: initialDataOther, backgroundColor: "rgba(244, 143, 177, 0.8)" },
{ label: "System", fill: true, data: initialDataOther, backgroundColor: "rgba(255, 235, 59, 0.8)" },
{ label: "IRQ", fill: true, data: initialDataOther, backgroundColor: "rgba(100, 181, 246, 0.8)" },
{ label: "Idle", fill: true, data: initialDataIdle, backgroundColor: "rgba(150, 150, 150, 0.4)" }
]
},
options: {
scales: {
xAxes: [{ stacked: true }],
yAxes: [{ stacked: true }]
},
plugins: {
stacked100: { enable: true }
}
}
});
console.log("Chart created: " + this.usageChart.data);
The problem is when I try to update the chart, this.usageChart.data is undefined. In fact, in that last console.log() call during initialization, it is also undefined. I cannot see what I am doing wrong. I am loading a plugin which allows a Line chart to be drawn as stacked with area between lines representing percentage. I don't know if perhaps this plugin is the issue, but I am getting no errors about it and the code was more or less taken verbatim from the plugin's example code.
Here is the code where I update the chart:
//from componentDidUpdate
usages['User'] = userUsage;
usages['System'] = sysUsage;
usages['IRQ'] = irqUsage;
usages['Idle'] = idleUsage;
console.log("updating chart");
this.usageChart.data.datasets.forEach((dataset) => {
dataset.data.shift();
dataset.data.push(usages[dataset.label]);
});
this.usageChart.update();
console.log("chart updated");
I did create a fiddle (I just copied your code into custom component) for you and there is no error in my case.
I think that there is error around here, as your chart is not being updated properly:
this.usageChart.data.datasets.forEach((dataset) => {
dataset.data.shift();
dataset.data.push(usages[dataset.label]);
});
Corrected version:
You were wrongly updating the data sets:
this.usageChart.data.datasets.forEach((dataset) => {
dataset.data.shift();
dataset.data = usages[dataset.label];
});
Please check the working fiddle and compare it with your project.
Turns out I was using the wrong npm package.
Be warned, somebody has been sitting for 2 years on the name chartjs with an outdated, stale github repo. The real package name is chart.js. Very annoying.

Categories

Resources