How can i set piechart data's values with arrays name jschart - javascript

I use piechart with javascript(jschart graphic library). When i set the piechart data's values with arrays name the piechart doesn't work. if i use the static variable the piechart works how can i solve that?
this is static variables
function piechart()
{
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Galatasaray", "Fenerbahce", "Besiktas", "Diger"],
datasets: [{
data: [12,4,19,3],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
]
}]
},
options: {
responsive: true,
scales: {
beginAtZero: true
}
}
});
}
this is arrays name
function piechart()
{
int dizim=[5,9,8,7];
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Galatasaray", "Fenerbahce", "Besiktas", "Diger"],
datasets: [{
data: dizim,
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
]
}]
},
options: {
responsive: true,
scales: {
beginAtZero: true
}
}
});
}

please visit this site..
same question already answered
draw pie chart from arrays in highcharts
hope this works

You can make it work by changing int dizim=[5,9,8,7]; by var dizim=[5,9,8,7];

Related

How to create a chart with chartjs.org with data from an array?

I try to create a website with a bar-chart on it. I like to use ChartJs.
There are some good examples, but I don't know how to visualise the data if the data is an array.
var myArray = [{
year: '2016',
value: 5
},
{
year: '2017',
value: 9
},
{
year: '2018',
value: 4
}
];
How do I loop throu myArray to create a bar chart like this one in the example?
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['2016', '2017', '2018'],
datasets: [{
label: '# of Votes',
data: [5, 9, 4],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Thanks for your help!
Best, Marius
You can map your array of objects, getting only the value you need.
I did it by var values = myArray.map((x) => x.value) and then using values as the value to the data property inside chart options.
For the labels, you can use the same logic, but with x.year.
Below code represents an example:
var myArray = [{
year: '2016',
value: 5
},
{
year: '2017',
value: 9
},
{
year: '2018',
value: 4
}
];
//FILTER THE VALUES
var values = myArray.map((x) => x.value)
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['2016', '2017', '2018'],
datasets: [{
label: '# of Votes',
data: values,
borderWidth: 1,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="300" height="150"></canvas>
If, for some reason (browser maybe), you cant use arrow functions, then go with:
var values = myArray.map(function(x) {return x.value})

ChartJS: Get value from another another Chart

I have two charts, First chart shows the breakup of Shirt sales.
Second is the comparison of Blue Shirt vs Blue Trouser sales.
I want to import the Blue Shirt value from the first Chart to Second chart.
Here is the Code with two charts:
var ctx = document.getElementById("myChart1").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: 'Shirts',
data: [10, 10, 15, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
}
});
var ctx = document.getElementById("myChart2").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Blue Shirts", "Blue Trousers"],
datasets: [{
label: 'Sales',
data: [10, 8],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
}
});
Here is the JSFiddle (https://jsfiddle.net/kingBethal/L8x790fn/15/).
I found this thread describing getting data from click events: Click events on Pie Charts in Chart.js
I made also made a new fiddle here where it logs a chart object containing the chart data on chart click: https://jsfiddle.net/btnL9d2a/16/
myChart1Canvas.onclick = function(evt) {
var activePoints = myChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
// `chartData` will be an object in the format {'Labels' : Array, 'datasets' : Array}.
console.log(chartData);
}
};
chartData.datasets[0].data is an array of the clicked-on chart's data.

Chart.js passing value data dynamic

I am want to use data and level dynamic by ajax, so i am using as below but not working.
My ajax return data in json_encode of php.
My code is:
success: function (result) {
result = JSON.parse(result);
var labels = result['labels'];
var data = result['data'];
//console.log(data);
var ctx = document.getElementById("chartbtc");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [labels],
datasets: [{
label: 'Market Price (USD)',
data: [data],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
}
}
});
}
But chart is not generating:
Ajax result is:
{"labels":"13-Nov-2017, 14-Nov-2017, 15-Nov-2017, 16-Nov-2017, 17-Nov-2017, 18-Nov-2017, 19-Nov-2017, 20-Nov-2017, 21-Nov-2017, 22-Nov-2017, 23-Nov-2017, 24-Nov-2017, 25-Nov-2017, 26-Nov-2017, 27-Nov-2017, 28-Nov-2017, 29-Nov-2017, 30-Nov-2017, 01-Dec-2017, 02-Dec-2017, 03-Dec-2017, 04-Dec-2017, 05-Dec-2017, 06-Dec-2017, 07-Dec-2017, 08-Dec-2017, 09-Dec-2017, 10-Dec-2017, 11-Dec-2017, 12-Dec-2017","data":"6550.22, 6635.41, 7301.42, 7815.03, 7786.88, 7817.14, 8007.65, 8255.59, 8059.8, 8268.03, 8148.94, 8250.97, 8707.4, 9284.14, 9718.29, 9952.5, 9879.32, 10147.37, 10883.91, 11071.36, 11332.62, 11584.82, 11878.43, 13540.98, 16501.97, 16007.43, 15142.83, 14869.8, 16762.11, 17276.39"}
Since you have provided your ajax result, this will not work with the chart generation. In your case result["labels"] is a string and you are just making a list with 1 element which is the whole string(which is not valid for the labels property and will not work). What you should do is split the string, format it correctly and then supply it as a list to the labels property. Easiest way would be to use the split() function, and in your case you could split by ", ". Although I would recommend to implement a better response if its possible (have it something like so: {"labels": ["13-Nov-2017", "14-Nov-2017", ...]}).
Hope this helps!
For the first time you can fill the chart with your own value, but when it is coming for dynamically appending data then you should remove the canvas element and regenerate it. So that your data will get appended dynamically on chart.
You can try something like this.
<canvas id="chartbtc" class="canvasChart"></canvas>
<script>
dynamicDataAppendOnChart(labels, data); // On page loading you will be having your own data so you can pass them, or if you want that to be happen with ajax when page loading itself you can trigger the click event.
$('#btnClick').trigger('click');
// You will be calling the function with click event...
$('#btnClick').on('click', function () {
var data = '', labels = '';
$.ajax({
url: url,
type: "POST",
data: data,
async: isAsync,
success: function (result) {
result = JSON.parse(result);
labels = result['labels'];
data = result['data'];
}
});
dynamicDataAppendOnChart(labels, data); // Now you can call the function by passing labels and data
});
function dynamicDataAppendOnChart() {
$('#chartbtc').remove();
$('#appendTheCanvasElement').append('<canvas id="chartbtc" class="canvasChart"><canvas>'); // This would create new canvas element every time and removes the older one.
var ctx = document.getElementById("chartbtc");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [labels],
datasets: [{
label: 'Market Price (USD)',
data: [data],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
}
}
});
}
</script>
Try This.
Declare label and data as
var labels = result['labels'].split(","); // Return Array of Strings Of labels
var data = JSON.parse("[" + result['data'] + "]");// return array of data
Chage
labels: [labels],
data: [data],
to
labels: labels,
data: data,
Because it already in array

How does one add data to a Chart in an ajax call?

I am trying to add data obtained from an ajax call to a chart using Chart.js.
The following code is not working:
$(document)
.ready(function () {
fetchBeds($("#site").val());
var ctx = $('#paretoChart');
var paretoChart = new Chart(ctx);
fetchChartData(1, '2016-10-28', '2016-11-2', paretoChart);
});
function fetchChartData(bed, start, end, chart) {
$.ajax({
url: "/reports/fetchChartData",
type: "GET",
data: {
bed: bed,
start: start,
end: end
},
dataType: "json",
success: function (response) {
var chartData = {
labels: response.data.labels,
datasets: [{
label: 'Pareto of Events',
data: response.data.chartData,
}]
};
chart.data = chartData;
console.log(chart);
chart.update();
}
});
}
When run, it doesn't generate any errors (my ajax call is working fine, verified in firefox). Simply nothing happens. I have a feeling it has to do with how I am applying the data to the chart. If I take the example data from the chart.js website and use that directly in the new Chart(...) call, it works fine.
Is it even possible to apply new data after the chart has been created?
Here is the data returned from the ajax call, just in case:
{"result":true,"message":null,"data":{"labels":["Plant","Process"],"chartData":["1","1"]}}
Thank you!
Alright I got the newest ChartJS and tried it out with your scenario.
My html:
<canvas id="myChart" width="200" height="200"></canvas>
Creating the chart:
$(function () {
var ctx = $("#myChart");
var myChart = new Chart(ctx, { type: 'bar', data: { labels: [], datasets: [] } });
UpdateChart(myChart)
});
I had to specify the type and a data object with empty labels and datasets for it to even render on the screen as an empty chart.
My function that updates the chart:
function UpdateChart(chart) {
var data = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
}
chart.data.labels = data.labels
chart.data.datasets = data.datasets
chart.update()
}
I tried doing chart.data = data but that didn't work for me. I had to specifically update data.labels then data.datasets before updating.
Worked fine by me, see my exact code below.
You have to make sure that you are using the updated .js file of the chart.js plugin. Of course, you have to include Jquery plugin on top of your every javascript file.
For this replication, I used the cdn provided by jquery and chart.js.
<canvas id="chart" height="400px" width="400px"></canvas>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.js"> </script>
<script>
$.ajax({
url: "http://localhost:8081/chart.php",
dataType: "json",
success: function(response)
{
var ctx = document.getElementById("chart");
var myBarChart = new Chart(ctx, {
type: 'pie',
data: {
labels: response.data.labels,
datasets: [{
label: 'Number of Active Customers',
data: response.data.chartData,
backgroundColor: [
'rgba(75, 192, 192, 0.2)',
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(75, 192, 192, 1)',
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
}
});
}
});
</script>
chart.php file contains only the response JSON code as you may see below.
{
"result":true,
"message":null,
"data":{
"labels":[
"Plant",
"Process"
],
"chartData":[
"10",
"1"
]
}
}

How to draw Horizontal line on Bar Chart Chartjs

I have the following script of drawing bar chart and I wanna add horizontal line on particular y dot. I was trying following example link and I just substituted Chart.types.Line.extend with Chart.types.Bar.extend
but as a result I'm getting can not read property extend of undefined
So can someone help to implement above example which in the link properly or suggest another decision
my source code without horizontal line
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
},
}]
},
}
});
You can use Chart.js plugins to do that. Plugins let you handle specific events such as beforeUpdate or afterDraw and are also easy to implement :
Chart.pluginService.register({
afterDraw: function(chart) {
// Code here will be triggered ... after the drawing
}
});
An easy way to do it is to simply draw a line like you would you on a simple canvas element, after everything is drawn in your chart, using the lineTo method.
Here is a small example (and its related code) of how it would look like :
With the answer from #tektiv, your yAxis always starts at 0.
This is a working example without the use of yAxe.min, so
you can use it (for example, with beginAtZero:false) and the yAxe scales automatically with your data.
Line plugin:
var canvas = document.getElementById("barCanvas");
var ctx = canvas.getContext('2d');
Chart.pluginService.register({
afterDraw: function(chart) {
if (typeof chart.config.options.lineAt != 'undefined') {
var lineAt = chart.config.options.lineAt;
var ctxPlugin = chart.chart.ctx;
var xAxe = chart.scales[chart.config.options.scales.xAxes[0].id];
var yAxe = chart.scales[chart.config.options.scales.yAxes[0].id];
ctxPlugin.strokeStyle = "red";
ctxPlugin.beginPath();
lineAt = yAxe.getPixelForValue(lineAt);
ctxPlugin.moveTo(xAxe.left, lineAt);
ctxPlugin.lineTo(xAxe.right, lineAt);
ctxPlugin.stroke();
}
}
});
Chart:
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
lineAt: 14,
scales: {
yAxes: [{
ticks: {
beginAtZero:false
}
}]
},
}
});

Categories

Resources