Highcharts: Updating a Pie Chart with setData() - json

I am trying to work out how to update a Highcharts pie chart but for the life of me cannot seem to get it working right.
I have looked over the documentation and have been able to get a bar and line and spline graph to update fine but when using this function for pie charts it just does not work.
I am currently feeding in:
item.setData([["none", 100]], true);
Where item equals the series like so:
$.each(browser_chart.series, function(i, item){
if(item.name == 'Browser share'){
console.log(data.browsers);
item.setData([["none", 100]], true);
}
});
Which as shown in the demos is how the data for a pie chart is formatted. Problem is it cannot seem to read the series correctly. I try:
item.setData([\"none\", 100], true);
And it seems to do something but cannot read the x and y values right (which of course means it's wrong).
Can anyone here point me in the direction to get this working?
Thanks,

Edited:
When you set a new data you have to set as array of arrays for all pie parts in this case.
In my Example I have six categories, so I've to set data for all of them.
So, in this case you have to do something like:
var seriesData = [];
$.each(browser_chart.series, function(i, item) {
if(item.name == 'Browser share'){
seriesData.push(["serie"+i, someNumber]);
}
});
chart.series[0].setData(seriesData, true);

I have marked Ricardos answer however my question involved a tad more that I didn't explain properly.
I was updating the pie chart through AJAX from JSON generated by a PHP Backend. When I applied new data to the pie chart it would break.
Using Ricardos answer I was able to find out it is because I have a different number of points so I cannot just update the pie chart I must remake it like so:
browser_chart_config.series[0].data = data.browsers;
browser_chart = new Highcharts.Chart(browser_chart_config);
This will allow you to update a chart when you have a different number of points.
Hope it helps,
EDIT: I also found out that this is a known issue with HighCharts: https://github.com/highslide-software/highcharts.com/issues/542

//initialise
var new_data;
new_data = [{ name: 'load percentage', y: 10.0, color: '#b2c831' },{ name: 'rest', y: 60.0, color: '#3d3d3d' }];
function requestData()
{
$.ajax({
url: 'live-server-data.php',
success: function(point)
{
var series = chart.series[0];
var y_val = parseInt(point[1]);
var x_val = 100 - y_val;
console.log(point[0]+ "," +point[1] );//["0"]
new_data = [{ name: 'load percentage', y:y_val, color: '#b2c831' },{ name: 'rest', y:x_val, color: '#3d3d3d' }];
series.setData(new_data);
// call it again after one second
},
cache: false
});
}

Related

Highcharts Ordinal Issue

I am struggling to understand why I cannot get the ordinal aspect of my spline type chart to work correctly! I created a series of bar charts a long time ago but having not done anything like this in years I'm a tad clueless and needing some guidance, I've spent hours trying different methods and nothing works wether using Highcharts or highstock.
The code I have in the head of my page is as follows:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'spline'
},
title: {
text: theTitle,
x: -20
},
xAxis: {
ordinal: false,
type:'datetime',
labels: {formatter: function() {return Highcharts.dateFormat('%b %e (%y)', this.value);}}
},
series: []
}
$.getJSON("data_weight_loss.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
The dates are in datestamp format in my MySQL database as "2022-06-28 09:02:45" and despite trying all sorts I'm confused to how I can get the dates in my chart to add the dates in that don't already exist?
This image shows the chart on how it currently looks but has no relevance as the dates that are missing means the chart is not very helpful. It's been a long time since I used Highcharts and even did anything like this but as a personal project I'd love to get my chart working with the ordinal aspect in place. Is there anything glaringly obvious that I have done wrong?
The data for instance is like this if I look directly in the data call from the php page.
[{"name":"Date","data":[1651695362000,1652140800000,1652227200000,1652313600000,1652400000000,1652918400000,1653264000000,1654214400000,1654473600000,1654560000000,1654819200000,1655164800000,1655251200000,1655424000000,1655683200000,1656288000000]},{"name":"Weight","data":[2188,2000,1986,1962,1948,1868,1834,1744,1728,1720,1702,1682,1676,1666,1652,1622]}]
Any help would be appreciated, thank you.

Exclude a specific series from exporting to csv

I'm using HighCharts library to plot some data in gauge chart. My chart looks like the image below.
To achieve this plot, I'm using solid gauge and gauge together using series option, (solid gauge for the semicircular and gauge for the dial.)
...
series: [
{
name: 'solidgauge',
type: 'solidgauge',
data: [data.value],
...
},
{
name: 'gauge',
type: 'gauge',
data: [data.value],
...
},
]
...
Obviously the data for both series is identical, so when I export the chart into csv file, the library create two columns with same data and I want to change this behavior and export only one of series, but after a lots of search, I couldn't find any option in highcharts to exclude a specific series.
How can I do that? (I'm not familiar with exporting customization, answer with little code sample would be great for start creating my own.)
You can wrap the getCSV method and hide the series befere the proceed:
var H = Highcharts;
H.wrap(H.Chart.prototype, 'getCSV', function(proceed) {
var result;
this.series[1].hide();
result = proceed.apply(this, Array.prototype.slice.call(arguments, 1));
this.series[1].show();
return result;
});
Live demo: https://jsfiddle.net/BlackLabel/109a7vek/
Also, you can edit the generated data in the exportData event:
H.addEvent(H.Chart, 'exportData', function(e){
e.dataRows.forEach(function(el){
el.splice(2, 1);
});
});
Live demo: https://jsfiddle.net/BlackLabel/du7nz2hy/
Docs: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts

Multi-checkboxes And Chart Data

I try out to create a Data visualization with Chart.js.
My question is quite simple...
I have multi with different id.
Checking an input "from" to an input "to"
you will able to get data in your chart,
If you check A to B you get some Data, if you check A to C some others... etc...
so I use multi condition to define the data must be shown in my Chart.
here my code,
<input id="DFN001" type="checkbox" name="DFN001" onclick="check()" value="from" >From DFN001</li>
and my JavaScript
<script>
var ctx1 = document.getElementById("chart_1").getContext("2d");
var data = datas1 ;
function validate(){
var DFN001 = document.getElementById('DFN001');
if (DFN001.checked){
datas1 = [10,15,20,85,30,35,40];
}else{
alert("You didn't check it! Let me check it for you.")
}
}
var lineChartData1 = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
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
}
]
}
document.getElementById('generate_1').onclick = function()
{
window.myPie = new Chart(ctx1).Line(lineChartData1,{
responsive: true
});
};
</script>
but when I try it, I get this error... "Uncaught ReferenceError: datas1 is not defined" ...
Can Someone Help me ? or there is and other way do make it ?
thanks a LOT !
Best Regards, and Nice Day,
Mirko
You have a couple of program flow related stuff you have to take care of.
datas1 needs to be initialized before you attempt to set data using it. So you need to call validate(), not just declare it. In validate(), datas1 will be set only if the checkbox is checked. For now, let's simply check it using HTML (when you add the rest of your code, just remember not to attempt setting data unless datas1 is set i.e. the corresponding checkbox is checked)
<input id="DFN001" type="checkbox" name="DFN001" onclick="check()" value="from" checked>From DFN001
Calling validate is pretty simple
...
validate();
var ctx1 = document.getElementById...
You need to call new Chart to actually render the chart. Something like
new Chart(ctx1).Line(lineChartData1);
Finally you need to have the canvas element in your HTML (I assume you already have this - just included for completeness)
<canvas id="chart_1"></canvas>
In short, you'll need to call the Chart initialization, data initialization, etc. (on your checkbox clicks) keeping the above in mind.
Here's a fiddle with all the above changes - http://jsfiddle.net/cy2spqrg/

Highcharts add series dynamically

I want to add some series (I get the series data from a webservice as a 3dim array (and returning it as json) - I dont know the number of series I will get, so I have to load the series data dynamically).
In javascript I am building an object: (like this highstock example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/compare/)
seriesOptions[i] = {
name: namearray[i],
data: dataarray
};
e.g. result: [Object { name="Series", data=[[1041375600000, 29,9]]}]
I was trying to add the series like this:
$.each(seriesOptions, function (itemNo, item) {
chart.addSeries({
name: item.name,
data: item.data
}, false);
});
chart.redraw();
But the chart draws the series kinda weird and doesnt convert to timestamp to date.
Are there any problems with my chart data from the webservice?
Here is my code: http://jsfiddle.net/DGdaf/2/
Thanks for any help so far.
EDIT
It seems like the chart ignoeres all the default values of timeline/zoom value.
I have no idea why it doesnt display these components.
The problem could be, that I am drawing the chart after the initialization?
chart = new Highcharts.Chart(options);
But I have to do it cause of the dynamic series loading.
EDIT2
I am not sure if I am loading too much data or something. I cant create my series dynamically.
for(i=0; i<seriesOptions.length; i++){
chart.addSeries({
name: seriesOptions[i].name,
data: seriesOptions[i].data
}, true);
};
Set for your yAxis:
yAxis: {
type: 'datetime'
}
See fiddle
EDIT:
Timeline / zoom
http://jsfiddle.net/DGdaf/5/
Edit:
Use callback to add series, when chart is ready. However, why don't you add these series when chart is created?
chart = new Highcharts.Chart(options, function(ch) {
$.each(seriesOptions, function (itemNo, item) {
ch.addSeries({
name: item.name,
data: item.data
}, false);
});
chart.redraw();
});

How to Update the value of point in Highchart?

I have a Highchart that is receiving JSON data via AJAX and jQuery in setInterval function,when i use series.data[i].y = response[i].y , the value of y is change ,but dosent Display in chart and the hight of point has previous value but in tooltip show recent value ? and the x value dosent changhe at all, please help me how to update the the x and y value if it is changhed?
chart:{ renderTo: 'container',
zoomType: 'xy',
plotBackgroundImage: 'graphics/skies.jpg',
events: {
load: function () {
var series = this.series[0];setInterval(function () {ajax({type: "POST",url: "/Home/GetData",data: null),contentType: "application/json; charset=utf-8",success: function (response) { for (var i = 0; i < response.length; i++) { if (series.data[i].y =response[i].y || series.data[i].category != response[i].x) { series.data[i].y =response[i].y; series.data[i].category = response[i].x;} }}, dataType: "json",failure: ajaxCallFailed });}, 50000);}
You should not directly modify the this.series[0] object. Highcharts has api calls that you can use, which should be uses for correct results and not breaking anything unintentionally.
Here is a list of methods supported by the series object # http://www.highcharts.com/ref/#series-object
You may want to use addPoint or setData, as per your requirements.
I don't recommend doing it the say you are doing, but try calling the redraw method (this.redraw()) after you do your magic, http://www.highcharts.com/ref/#chart-object