I am trying to pass in my_series to series in highcharts to graph stacked bars. From my php, I get hash, which is like this:
{"Oat":{"10":"AA","11":"H"},"Brown Rice":{"10":"AA","11":"BB"}}
I actually dont know what is wrong with my code. I think it should work, but when I run it, I do not see anything on the screen. I checked that sample_name has "Oat" and "Brown Rice", which is what I want.
What I eventually want is a color-coded stacked bar graph that has samples on the yAxis and position on the xAxis. I think I almost got to what I want, it's just a problem with making an actual graph.
Thank you!
$(function() {
var allele_str = [];
var sample_name = [];
var hash = {};
var my_series = {
data: []
};
var position = [];
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'bar',
zoomType: 'xy',
inverted: true
},
title: {
text: 'Gene'
},
xAxis: {
categories: [],
},
legend: {
enabled: false
},
yAxis: {
title: {
text: 'Position'
},
labels: {
enabled: false
}
}
plotOptions: {
series: {
stacking: 'normal'
}
}
series: []
};
$.getJSON('6K_load.php', function(data) {
sample_name = Object.keys(data);
options.xAxis.categories.push(sample_name);
for (var x in sample_name) { // sample Oat, BR
for (var k in data[sample_name[x]]) { // pos
series.name = k;
var z = data[sample_name[x]][k];
hash[z] = 1;
allele_str.y = hash[z];
if (z === 'AA') {
allele_str.color = 'grey';
}
if (z === 'BB') {
allele_str.color = 'blue';
}
if (z === '--') {
allele_str.color = 'white';
}
if (z === 'H') {
allele_str.color = 'red';
}
my_series.data.push(allele_str);
}
options.series.push(my_series);
}
var chart = new Highcharts.Chart(options);
});
});
The problem is that you not parse your data to number value, you need to use parseFloat() in this line
my_series.data.push(parseFloat(allele_str));
Related
I am making pie chart from high chart library. I want to change color of each slice in pie chart
How can i do this ? My code is -
var colors = ["color:'#2a8482'","color:'#64DECF'","color:'#BCCDF8'"];
var responseData = {"2":40,"1":30}
var obj = $.parseJSON(responseData);
var dataArrayFinal = Array();
var value = Array();
var name = Array();
var j = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
name[j] = "name:'"+key+"'";
value[j] = obj[key];
j++;
}
}
for(k=0;k<name.length;k++) {
var temp = new Array(name[k],value[k],colors[k]);
dataArrayFinal[k] = temp;
}
$(function () {
new Highcharts.Chart({
chart: {
renderTo: 'container'+counter,
type: 'pie',
height: 280,
width: 280
},
title: {
text: ' '
},
tooltip: {
valueSuffix: '%',
positioner: function () {
return {
x: this.chart.series[0].center[0] -
(this.label.width / 2) + 8,
y: this.chart.series[0].center[1] -
(this.label.height / 2) + 8
};
}
},
series: [{
name: 'Answer',
size: '100%',
innerSize: '65%',
data: dataArrayFinal
}]
});
});
In this graph is coming but colors are not changed. They are taking default color.
Highcharts.setOptions({
colors: ['#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
It should work that way ;-)
if you change your color-array to:
var colors = ["#2a8482","#64DECF","#BCCDF8"];
and then at the beginning of your function:
$(function () {
add the following code:
Highcharts.getOptions().plotOptions.pie.colors = colors;
this should do the trick.
Example of coloring can be found in this JSFiddle, created by the developers of HighCharts:
http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/pie-monochrome/
I am trying to create a line chart using Flot that shows the month and year on the x axis corresponding to a number on the y axis.
Here is my code:
var data= [];
var y = 1;
var x;
var record=xmlDoc.getElementsByTagName("record");
for(i=0;i<record.length;i++)
{
x = record[i].getElementsByTagName("date_of_consent")[0].childNodes[0].nodeValue;
x = x * 1000
y = y + i;
newArray = [x, y];
data.push(newArray);
}
var dataset = [{label: "Enrollment Over Time",data: data}];
var options = {
series: {
lines: { show: true },
points: {
radius: 3,
show: false
}
}
xaxis: {
mode: "time",
timeformat: "%y/%m"
}
};
$(document).ready(function () {
$.plot($("#flot-placeholder"), dataset, options);
});
For reference the date_of_consent field has values similar to this: 1376092800000. The problem seems to be converting this number to a date. I would appreciate any suggestions. Thanks.
You have a javascript syntax error:
var options = {
series: {
lines: { show: true },
points: {
radius: 3,
show: false
}
}, <-- YOU ARE MISSING THIS COMMA!!
xaxis: {
mode: "time",
timeformat: "%y/%m"
}
};
As you code, frequently inspect the javascript console for errors.
I am new to Highcharts, Sharepoint and JS. What I need to do is make each bar link to a SharePoint view
This code gets the data
IWSChartBuilder.EngagementsSegmentChart = function () {
var load = function () {
var year = new Date().getFullYear();
//Variable to hold counts
var countArray = [];
$.when(
//Consulting Engagements List
IWSChartBuilder.RESTQuery.execute("valid REST query")
).done(
function (engagements1) {
var dataArray = [];
var countArray = [];
//Get data from Consulting Engagements list
var results = engagements1.d.results;
for (var i = 0; i < results.length; i++) {
for (var i = 0; i < results.length; i++) {
dataArray.push(results[i].Segment);
}
}
var baseUrl = "valid url";
countArray = IWSChartBuilder.Utilities.buildCategoryCountsWithLink(countArray, dataArray, baseUrl);
//Put data into format for stacked bar chart
var seriesData = [];
var xCategories = [];
var links = [];
for (var i = 0; i < countArray.length; i++) {
xCategories.push(countArray[i].name);
seriesData.push(countArray[i].y);
links.push(countArray[i].url);
}
//Build Chart
IWSChartBuilder.Utilities.loadColumnChartWithLink(links, xCategories, seriesData, "#engagementSegmentChart", "Engagements by Segment", "Total Projects");
}
).fail(
function (engagements1) {
$("#engagementSegmentChart").html("<strong>An error has occurred.</strong>");
}
);
};
return {
load: load
}
}();
//code to display chart
loadColumnChartWithLink = function (xCategories, seriesData, divId, chartTitle, yAxisTitle) {
//Build Column Chart
$(divId).highcharts({
chart: {
type: 'column'
},
credits: {
enabled: false
},
title: {
text: chartTitle
},
xAxis: {
categories: xCategories,
allowDecimals: false,
labels: {
rotation: -45,
align: 'right'
}
},
yAxis: {
min: 0,
allowDecimals: false,
title: {
text: yAxisTitle
}
},
legend: {
enabled: false
},
plotOptions: {
bar: {
dataLabels: {
enabled: false
}
},
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
location.href = this.options.url;
}
}
}
}
},
series: [{
name: yAxisTitle,
data: seriesData
}]
});
},
Any help is greatly appreciated
Mark
You need to adapt your data to create objects as points, like in the example:
{y:10,url:'http://google.com'}
and then catch click event on serie's point.
http://jsfiddle.net/2tL5T/
(function($){
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var i=0;
var chart = new Highcharts.Chart({
chart: {
type: 'spline',
renderTo: 'container',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var Name = new Array();
Name[0] = "Random data";
Name[1] = "Volvo";
var length=chart.series.length;
var flag=0;
var index=0;
var x = (new Date()).getTime(), // current time
y = Math.random();
for (var k=0;k<Name.length;k++) {
for(var j=0;j<chart.series.length;j++) {
if(chart.series[j].name==Name[k]) {
flag=1;
index=j;
x = (new Date()).getTime();
y = Math.random();
break;
}
}
if(flag==1) {
chart.series[index].addPoint([x, y], true, true);
flag=0;
} else {
chart.addSeries({name: '' + Name[k] + '', data: [] });
chart.series[length].addPoint([x, y+1], true);
length=length+1;
}
}
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});
})(jQuery);
I am able to add series and add point in charts but the series that I add after initialization, which is "volvo", is not drawing lines between its points. What might be the problem?
And is there any other way of comparing arrays and adding points without a for-loop? Because I can get millions of series at times and I don't want to be looping over arrays to check if it exists or not. So is there any efficient way of finding wheteher a list already exists, and if it does what is its index?
here is its fiddle: www.jsfiddle.net/2jYLz/
It is related with fact that you have enabled shifting in addPoint() when you add new serie. In other words, shifting remove first point and add new in the end of serie. So when you have one point it caused your scenario. So you need to disable shipfing, and when lenght of series.data achieve i.e 10 points, shifting should be enabled.
×212414
×123754
I am calling a PageMethod in codebehind.aspx.cs file which returns me a string array[] in the javascript code in the aspx page the problem at hand is that string array returns Time(X axis-Value),Data/Name(Y axis Value),Type(Defines the type of chart (Spline or Column)) from a WEB SERVICE. I am using that data to add series dynamically to the chart. Using the function chart.AddSeries() but I am unable to do so.
Can anyone please guide me how to do that and upon doing that I want to add points to the particular Series.
Please Note that I would be displaying to types{Spline and Column} on the same chart.
<script type="text/javascript">
alert("Bingo");
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'ltrChart',
type: 'spline',
marginRight: 10,
events: {
load: function () {
PageMethods.GetSingleValue(function (result) {
var Name = new Array();
var Type = new Array();
var Data = new Array();
var Time = new Array();
var Ser = chart.series;
for (var i = 0; i < 6; i++) {
Type[i] = result[i].split('-')[0];
Name[i] = result[i].split('-')[1];
Data[i] = result[i].split('-')[2];
Time[i] = result[i].split('-')[3];
chart.addSeries({ name :Name[i], data : [ [Time[i], Data[i]] ] }, true, true);
/* Test Method To ensure data Fetching */
// alert(Type[i] + Name[i] + Data[i] + Time[i]);
// alert(result[i]);
}
})
//console.log(typeof PageMethods.GetSingleValue);
// PageMethods.GetSingleValue();
setInterval("PageMethods.GetSingleValue()", 5000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
//type: 'datetime',
//tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Test Data',
data: [[10, 50], [15, 55]]
}]
});
});
});
</script>
This is what I've done and works like a charm. On a side-note, since you mentioned aspx page, why don't you just buy the dot net highcharts library? It makes life a lot easier if you're a dot net fan!
I am initially creating a chart with 5 elements, and then using the "iterated" JSON serialized string to pass data to client-side. Traversing the elements gives me a dynamic live chart!
Highcharts chart = new Highcharts("livechart")
.InitChart(new Chart
{
Events = new ChartEvents { Load = "ChartEventsLoad" }
})
.SetSeries(initialSeries)
.SetXAxis(new XAxis { Categories = lsst.ToArray() })
.AddJavascripVariable("iterated", iterateData.ToString())
.AddJavascripVariable("index", "5")
.AddJavascripFunction("ChartEventsLoad",
#"// set up the updating of the chart each 5 seconds
var result = iterated;
var theseries = eval(result); // De-serializing the JSON object
var loopseries = function() {
var sseries = livechart.series[0]
,shift = sseries.data.length > 5; // shift if the series is longer than 5;
sseries.addPoint(theseries[0].data[index], true, shift);
var sseries1 = livechart.series[1]
sseries1.addPoint(theseries[1].data[index], true, shift);
index++; };
setInterval(loopseries, 5000);")
You can add as many series as you like; you can use a loop if needed and the same code I've added as a function can be used to create the chart completely in Javascript.