I have been using highchart for graphical display of my records. HighChart works fine with my php variable with comma separated values in it. However, I couldn't get this done using javascript variable with comma separated values. Please help me with this. Your help is much appreciated. Thanks. My codes are shown below.
Javascript
<script type="text/javascript">
var res = [];
var data_graph = [];
function show_graphics(){
$.post("<?php echo base_url(); ?>main_controller/show_monthly_analytics_ajax", '', function(data){
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
data_graph = res.join(",");
console.log(data_graph );
} else{
console.log(data.notify);
}
},'json');
$('#container').highcharts({
chart: {
type: 'column',
margin: 75,
options3d: {
enabled: true,
alpha: 10,
beta: 25,
depth: 70
}
},
title: {
text: '3D chart with null values'
},
subtitle: {
text: 'Notice the difference between a 0 value and a null point'
},
plotOptions: {
column: {
depth: 25
}
},
xAxis: {
categories: Highcharts.getOptions().lang.shortMonths
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Sales',
data: [data_graph]
}]
});
}
</script>
When I look at the console, the values being showed of the variable array data_graph seems right but the chart never showed a graph. What is the problem with this?
Modification
<script type="text/javascript">
var res = [];
function show_graphics(){
$.post("<?php echo base_url(); ?>main_controller/show_monthly_analytics_ajax", '', function(data){
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
//aa = res.join(",");
console.log(res);
} else{
console.log(data.notify);
}
},'json');
$('#container').highcharts({
chart: {
type: 'column',
margin: 75,
options3d: {
enabled: true,
alpha: 10,
beta: 25,
depth: 70
}
},
title: {
text: '3D chart with null values'
},
subtitle: {
text: 'Notice the difference between a 0 value and a null point'
},
plotOptions: {
column: {
depth: 25
}
},
xAxis: {
categories: Highcharts.getOptions().lang.shortMonths
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Sales',
data: [res]
}]
});
}
</script>
Response
The data part/section for series property should be an array of numbers.
According to your explanation, your implementation is as if you would have the following:
series: [{
name: 'Sales',
data: ['1, 2, 1, 0'] // this is an array with one string element, which is wrong
}]
But, it should be:
series: [{
name: 'Sales',
data: [1, 2, 1, 0]
}]
See JSfiddle demo here
EDIT
Besides the change that I suggested above, consider that the $.post call is an async execution. Then, you should only draw the chart when data is 'ready' by moving $('#container').highcharts(...) block inside the success callback as follows:
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
$('#container').highcharts({
...
...
series: [{
name: 'Sales',
data: res
}]
});
} else {
console.log(data.notify);
}
Related
So What I am trying to do is that I am trying to create Plotline on a particular X value based on the data I have in an array.
There are 2 data arrays that I have :
featurex = [95,193,295,393,480,587,700,799,912,1015,1123,1230,1336,1443,1554] ;
featurey = [0,0,0,0,0,3,0,0,0,0,0,0,0,0,0];
Now What I am trying to do is that I am trying to Plot a plotline on X-axis where my Y-axis is 3 As you can see above.
I am able to do it statically, but I want it to be dynamic.
This is the Highchart's code that I am using.
Highcharts.chart('ppg', {
chart: {
type: 'line'
},
title: {
text: 'ECG Data'
},
subtitle: {
text: ''
},
xAxis:
for( i=0; i<featurex.length; i++)
{
if (featurey[i] == 3) {
plotLines: [
{
value: featurex[i],
color: '#005a9b94',
dashStyle: 'shortdash',
width: 100,
},
}
},
crosshair: false
},
yAxis: {
title: {
text: 'Peaks'
}
},
tooltip: {
enable: false
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: '',
lineWidth: 2,
data: yData,
animation: {
duration: 5000
}
},
{ type: 'scatter',
name: 'Installation',
data: zip(xPeak, yPeak),
animation: {
duration: 5200
}
},
]
});
});
});
</script>
Here the Plotline code under the Xaxis is the main area of concern.
It's throwing me an error :
Uncaught SyntaxError: Unexpected token for
Please guide me on what I am doing wrong.
Any Help is really appreciated. Thanks.
The problem is here,
xAxis:
for( i=0; i<featurex.length; i++)
Above is not valid javascript syntax.
If you need plotlines to be dynamic, pass a function that returns an array
xAxis: {
plotLines: generateDynamicPlotLines(),
}
And your function would be something like,
function generateDynamicPlotLines() {
const plotLines = [];
for(var i=0; i<featurex.length; i++) {
if (featurey[i] == 3) {
plotLines.push({
value: featurex[i],
color: '#005a9b94',
dashStyle: 'shortdash',
width: 100,
});
}
}
return plotLines;
}
Seems your plotLines assignment is missing a ] in your code, it should have been like this,
plotLines: [{
value: featurex[i],
color: '#005a9b94',
dashStyle: 'shortdash',
width: 100,
}],
}
Hope this helps!
I have been trying to customize an excellent jsfiddle that I was fortunate enough to be directed to in an earlier question here: Switching between many Highcharts using buttons or link text
I am very new to javascript programming (and highcharts also) and I am having some difficulties in retrieving my own data from a database. Currently I have set up my charts like the following:
$('chart1').ready(function() {
var options = {
chart: {
renderTo: 'chart1',
type: 'column',
marginTop: 40,
marginBottom: 75
},
legend: {
enabled: false
},
title: {
text: 'Revenues',
x: 25 //center
},
xAxis: {
title: {
text: ''
},
categories: []
},
yAxis: {
showInLegend: false,
tickAmount: 11,
endOnTick: false,
startOnTick: true,
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value, 0, '.', ',');
}
},
title: {
text: '<?php echo $unitCurr; ?>'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ Highcharts.numberFormat(this.y, 0,'.',',');
}
},
series: []
}
var tableName = '<?php echo $tableName; ?>'
$.getJSON("../../companies/charts/data.php", {id: escape(tableName)}, function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
At the bottom you will notice that I am using JSON to retrieve information from my database and everything works just fine. In my earlier question I was asking about how to switch charts using buttons instead and was directed to the following jsfiddle: http://jsfiddle.net/jlbriggs/7ntyzo6u/
This example consists of 3 charts but I have just been trying to manipulate the first chart in order to find out if I could make my own data display instead of the random data that is being generated:
var chart,
chartOptions = {},
chartData = {};
chartData.chart1 = randomData(25);
chartData.chart2 = randomData(10, true);
chartData.chart3 = randomData(65, true, 300);
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: chartData.chart1
}]
};
But no matter how much I tried, I just can't seem to change the "data: chartData.chart1" in such a way that it retrieve the arrays I get from my $.getJSON function. Can any of you help me explain why, for instance, the below code doesn't work?. Here I try to exchange the ChartData.chart1 array for my database data. I'm not experienced enough to tell whether its the whole random number generation part of the code that prevents it from working or if it's my understanding thats severely lacking. (I have made sure that the data from data.php is indeed available, since I can display it in a normal array when I try).
var chart,
chartOptions = {},
chartData = {};
chartData.chart2 = randomData(10, true);
chartData.chart3 = randomData(65, true, 300);
$.getJSON("../../companies/charts/data.php", {id: escape(tableName)}, function(json) {
chartData.chart1 = json[6]['data'];
});
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: chartData.chart1
}]
};
Any assistance you can provide will be greatly appreciated!
You're actually very close to something that will work. Your problem is related to the timing of async calls relative to inline code, and also the way assignments work in javascript.
As a quick example, here's some code:
x = {foo:5};
y = x.foo;
x.foo = 9;
At the end of this, x.foo is 9, but y is still 5.
Your line of code
chartData.chart1 = json[6]['data'];
doesn't execute until after the call to the server completes; it's contained within a call back function. However, this section of code
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: chartData.chart1
}]
};
executes immediately. See the problem? You've cooked the current value of chartData.chart into chartOptions.chart1 BEFORE the server call has completed. That's why you're not seeing your data.
Instead, try something like this:
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: []
}]
};
$.getJSON("../../companies/charts/data.php", {id: escape(tableName)}, function(json) {
chartOptions.chart1.series[0].data = json[6]['data'];
});
Now when your data comes back, you're putting it into the object that is actually being used to render the chart (once you click on the right button). Keep in mind that it's going to be empty until the server call completes.
I am having a list name aaa. It is an list of list
aaa[0] = [[{'a',1},{'b',2}]
aaa[1] = [[{'q',2},{'bd',0}]
aaa[2] = [[{'sa',3},{'bs',6}]
aaa[2] = [[{'sa',5},{'vb',8}]
I got the response from the model
Now I need to populate this value into Chart
My Chart will contain four lines for aaa[0] ,aaa[1] ,aaa[2] ,aaa[3]
Here is my High Chart Code
<script>
$(document).ready(function () {
//Default time zone
moment.tz.setDefault("America/New_York");
// Global option to disable UTC time usage
Highcharts.setOptions({
global: {
useUTC: false
}
});
// Chart configurations
var options = {
chart: {
renderTo: 'container2',
type: 'area',
marginRight: 45,
zoomType: 'x'
},
title: {
text: 'aaaa'
},
xAxis: {
type: 'datetime',
minRange: 8 * 24 * 3600000,
labels: {
format: '{value:%m-%d-%Y}',
rotation: 45
}
},
yAxis: {
title: {
text: 'count'
},
labels: {
formatter: function () {
return this.value;
}
}
},
plotOptions: {
area: {
marker: {
enabled: true,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: true
}
}
},
lineWidth: 1,
threshold: null
}
},
series: [{
fillOpacity: 0.1,
name: 'aaa',
pointInterval: 24 * 3600 * 1000,
pointStart: 1375295400000,
data: GetPercentage()
}]
};
// Rendering the Highcharts
chart = new Highcharts.Chart(options);
function GetPercentage() {
var data = #Html.Raw(JsonConvert.SerializeObject(Model.aaa));
// alert(data)
#foreach(var val in Model.aaa) //loop of getting a list from aaa
{
var percentages = [];
for (var x = 0; x < #val.Count; x++)
{
//Here I need to push the list
}
//percentages.sort(SortByDate);
// return percentages;
}
}
//Sort the array based on first array element
function SortByDate(a,b){
//alert(a[0] +" - " +b[0]);
return (a[0] - b[0]);
}
//Timeout function to reload page on everyone hour
setTimeout(function () {
location.reload(true);
}, 60* 60 * 1000);
//Progress bar to display feed delivery percentage
$('.progress .progress-bar').progressbar({
transition_delay: 500,
display_text: 'fill',
refresh_speed: 500
});
});
</script>
Could anyone help me to diplay a chart with four lines ?
Thanks in advance
Here you can see the series is an object array
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
});
You should add more objects into series array to create more than one line.
$(function () {
$('#containerGraph').highcharts({
chart: {
type: 'column'
},
title: {
text: ''
},
subtitle: {
text: ''
},
exporting: { enabled: false },
credits: { enabled: false },
xAxis: {
type: 'category',
title: {
text: 'Date'
},
labels: {
rotation: -45,
style: {
fontSize: '10px',
fontFamily: 'Verdana, sans-serif'
}
}
},
plotOptions: {
column: {
colorByPoint: true
}
},
yAxis: {
min: 0,
title: {
text: 'Time (minutes)'
}
},
legend: {
enabled: false
},
tooltip: {
//pointFormat: '<b>{point.y:.1f} minutes</b>{point.x:}'
formatter: function() {
return '<b>'+ this.y +'</b>'+
'minutes<br>'+ this.point.z + 'hi' ;
},
//shared: true
},
series: [{
name: 'Time',
data: [
['<?php print $buildDate[0]?>', <?php print $lastFifteenDurationArray[0]?>, <?php echo $svnHistory[0]?>],
['<?php print $buildDate[1]?>', <?php print $lastFifteenDurationArray[1]?>, <?php print $svnHistory[1]?>],
['<?php print $buildDate[2]?>', <?php print $lastFifteenDurationArray[2]?>, <?php print $svnHistory[2]?>],
['<?php print $buildDate[3]?>', <?php print $lastFifteenDurationArray[3]?>, <?php print $svnHistory[3]?>],
['<?php print $buildDate[4]?>', <?php print $lastFifteenDurationArray[4]?>, <?php print $svnHistory[4]?>],
['<?php print $buildDate[5]?>', <?php print $lastFifteenDurationArray[5]?>, <?php print $svnHistory[5]?>]
],
lang: {noData: "No Data Available"},
dataLabels: {
enabled: false
}
}]
});
});
The value of z-axiz in the tooltip shows Undefined in the chart.
I also tried this.point.config[2], but that doesn't work either.
When I debugged the code, the z-value in the data field is correctly resolved.
Is it because I have to specify type of data or something?
Can someone tell me what I am doing wrong?
In case you wan't a third dimension you'll need to define it like this: data = [{y: yValue, z: zValue, additional: additionalVal}], like this you can access this.point.z (and this.point.additional). Anyway, it seems that using the series X values as x-axis category label does not work while working with an array of objects. In order to make it run, do it like this:
xAxis: {
type: 'category',
categories: ['09-01-2015','09-01-2015'], /* your old x-data */
title: {
text: 'Date'
}
},
series: [{
name: 'Time',
/* data is now an array of objects */
data: [
{y:25, z:492076},
{y:26, z:496222}
],
}
updated Fiddle is here
For some reason I am unable to set the properites of a Javascript Object created in literal form.
Using PHP to write the Javascript code. The first chart Object chartObject1 displays correctly but the second chart chartObject2 does not display the title because I am attempting to set the title text property outside of the literal definition.
Why won't it let me set the property using chartObject2.title.text = "chart2"; ??
<?php
$chart_text = <<<EOD
<script type="text/javascript">
var chartObject1 = Object;
$(document).ready(function(){
chartObject1 = new Highcharts.Chart({
chart: {
renderTo: 'chart1',
type: 'bar'
},
title: {
text: 'chart1'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]},
{
name: 'John',
data: [5, 7, 3]}]
});
});
</script>
EOD;
print ($chart_text);
$chart_text = <<<EOD
<script type="text/javascript">
var chartObject2 = Object;
$(document).ready(function(){
chartObject2 = new Highcharts.Chart({
chart: {
renderTo: 'chart2',
type: 'bar'
},
xAxis: {
categories: ['Spiders', 'Grasshoppers', 'Scorpions']
},
yAxis: {
title: {
text: 'Bugs eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]},
{
name: 'John',
data: [5, 7, 3]}]
});
chartObject2.title.text = "chart2";
});
</script>
EOD;
print ($chart_text);
?>
because its a Highcharts object, you would need to use their api to change the text.
Like this:
chartObject2.setTitle({text: "chart2"});