Polar Area onclick event - javascript

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) {
}
}
}
});

Related

How to add text inside the doughnut chart?

Can anyone help me with the below js code?
I want to add text to the doughnut chart like the below image link.
var a = $("#myChart").get(0).getContext("2d");
var myChart1 = new Chart(a, {
type: "doughnut",
data: {
labels: ["Approved", "Declined"],
datasets: [
{
backgroundColor: ["#8DE08D", "rgb(233,122,122)"],
data: [55, 49]
}
]
},
options: {
responsive: true
}
});
take a look at this : https://jsfiddle.net/4rk1ucgx/
here you can see that at line 45 var text = "75%", of the code you can add whatever text you would like inside the doughnut chart

vue3 chart-js showing previous data on hover

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)

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>

Auto Generating Pie Chart Legend

I am trying to create a pie chart in JavaScript. I would like this chart to display in the legend only the labels that are non zero.
Does anyone have any ideas how this can be done?
Here is the code I have so far. Currently the legend of the pie chart shows all possible 12 Labels, even though 8 of these have zero value. "Data" will eventually be filled from a database and therefore it is important that this is an automated process.
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Astronomica", "Deuteronic", "Floral", "Galactic","Celestrial","Heliosphere","Jupiter","Interstella","Koronis","Eclipse,"Borealis","Lunatic"],
datasets: [{
data: [12.21, 15.58, 11.25, 8.32],
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
},
});
You can manage data before use they.
var ctx = document.getElementById("myPieChart");
var input_lables = ["Astronomica" , "Deuteronic", "Floral", "Galactic", "Celestrial", "Heliosphere", "Jupiter", "Interstella","Koronis", "Eclipse", "Borealis", "Lunatic"];
var input_values = [12.21, 15.58, 11.25, 8.32];
var output_lables = [];
var output_values = [];
for(var i=0;i<input_lables.length;i++){
if(!values[i]){
output_lables.push(input_lables[i]);
output_values.push(input_values[i]);
}
}
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: output_lables,
datasets: [{
data: output_values,
backgroundColor: ['#007bff', '#dc3545', '#ffc107', '#28a745'],
}],
},
});
if you went to automatic it just enough make a function like this code.
According with the documentation you can use the filter parameter in the label
http://www.chartjs.org/docs/latest/configuration/legend.html
and you can make a validation to validate the data and if it is 0 you can return false
Filter a legend Item with Chartjs.org V2.7

Chart.js is it possible to fire javascript when clicking on point on the graph?

Does anyone know if it is possible to fire a javascript event when clicking on a point on a Chart.js graph?
If so, how?
UPDATE: This is my current chart initialization script, based on feedback:
function RenderBasicAnalyticsChart(targetSelector, usersCreated, usersAuthenticated, contentDownloaded)
{
var ctx = $(targetSelector);
var chartObject = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
type: 'line',
label: 'Users created',
borderColor: 'rgba(0,169,224,1.0)',
pointBackgroundColor: 'rgba(0,169,224,1.0)',
backgroundColor: 'rgba(0,169,224,0.4)',
data: usersCreated
},
{
type: 'line',
label: 'Users signed in',
borderColor: 'rgba(120,170,0,1.0)',
pointBackgroundColor: 'rgba(120,170,0,1.0)',
backgroundColor: 'rgba(120,170,0,0.4)',
data: usersAuthenticated
},
{
type: 'line',
label: 'Assets downloaded',
borderColor: 'rgba(255,106,19,1.0)',
pointBackgroundColor: 'rgba(255,106,19,1.0)',
backgroundColor: 'rgba(255,106,19,0.4)',
data: contentDownloaded
}
]
},
options: {
defaultFontFamily: 'Open Sans',
responsiveAnimationDuration: 100,
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
quarter: 'MMM YYYY'
}
}
}]
}
}
});
$(targetSelector).click(function (e) {
var activePoints = chartObject.getElementsAtEvent(event);
if (activePoints.length > 0) {
var clickedDatasetIndex = activePoints[0]._datasetIndex;
var clickedElementIndex = activePoints[0]._index;
var value = chartObject.data.datasets[clickedDatasetIndex].data[clickedElementIndex];
console.log(clickedDatasetIndex + ' - ' + value['x']);
}
});
}
The issue I am now having is that my clickedDatasetIndex is always coming back as 0, regardless of which line I clicked.
Yes you sure can! Just use the .getDatasetAtEvent(e) or .getElementsAtEvent(e) prototype methods (depending on your needs). Here is more detail on what they do.
Looks for the element under the event point, then returns all elements at the same data index. This is used internally for 'label' mode highlighting.
Calling getElementsAtEvent(event) on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.
Here is an example for how to get the point that was clicked when there are more than 1 datasets. Assuming my canvas has an id of canvas and my chart instance is called myLine.
document.getElementById("canvas").onclick = function(evt){
var activePoints = myLine.getElementAtEvent(event);
// make sure click was on an actual point
if (activePoints.length > 0) {
var clickedDatasetIndex = activePoints[0]._datasetIndex;
var clickedElementindex = activePoints[0]._index;
var label = myLine.data.labels[clickedElementindex];
var value = myLine.data.datasets[clickedDatasetIndex].data[clickedElementindex];
alert("Clicked: " + label + " - " + value);
}
};
You can also experiment with this codepen example.

Categories

Resources