To pass dynamic json array to Highcharts Pie Chart - arrays

I passed json encoded string(eg. $TEXT2 consisting ["chrome","15","firefox","20"]) from xcode to an array(eg. arr) in javascript.Now I want to pass this array containing json string dynamically to Highcharts Pie. The HTML code is
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=20, user-scalable=no;" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Pie chart</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
var chart;
var arr = $TEXT2;
$(document).ready(function(){
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Interactive Pie'
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: []
}]
});
});
</script>
<body>
<br>
<!-- 3. Add the container -->
<div id="container" style="width: 300px; height: 350px; margin: 0 auto"></div>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
</body>
</html>
I am trying to use getjson method although m unaware of its usage.
Since i want to pass my array i.e arr to data[] in Highcharts,I am doing:
$.getJSON("arr", function(json) {
chart.series = json;
var chart = new Highcharts.Chart(chart);
});
Can anyone help me on dis.
Thanks in advance.

I would wrap the JSON call in the document.ready function and then wrap the plot call in the getJSON's success callback:
$(document).ready(function() {
$.getJSON("arr", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Interactive Pie'
},
tooltip: {
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
},
series: [{
type: 'pie',
name: 'Browser share',
data: json
}]
});
});
});
Of course for this to work, you should modify your backend code to return a properly formatted array of arrays that HighCharts expects:
[["chrome",15],["firefox",20]]
You could "fix" your returned array in the JS, but it would be better to do it in the JSON backend call.

<script type="text/javascript">
jQuery(document).ready(function () {
alert('call pie');
var data1 = $("#dataidd").val();
alert('pie data' + data1);
/*--------Pie Chart---------*/
$('#PieChartDiv').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Comparision and Analysis Report'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Issue Details',
// data: jQuery.parseJSON(data1)
data: JSON.parse(data1)
}]
});
});
</script>

Simply do :
Create array with Jquery as bellow :
$.each(data['values'], function(i, val) {
x_values_sub['name'] = i
x_values_sub['y'] = val
x_values.push(x_values_sub);
x_values_sub = {};
});
// Then call this array with HighCharts as data
series: [{
type: 'pie',
name: null,
data: x_values
}]
// Tested and it works with simple javascript object :
Object Part1Name: 25 Part2Name: 75__proto__: Object

You can bind chart with JSON data, directly. You just need to set the json property names as highchart standard. 'Y' for value and 'name' for label.
Your JSON should be as like follow:
[ { name: "Chrome", y: 25 }, { name: "Firefox", y: 20 } ]

Related

Highstock highcharts stacked column jQuery.getJSON array not working

I have developed a very simple column chart from a json three dimensional array:
0: timestamp in millliseconds
1:given recognition
2:received recognition
[[1490288274653,7,175],[1490374674653,1,1],[1490806674653,1,1],[1490979474653,3,3],[1491065874653,4,4],[1491411474653,6,0],[1491497874653,2,0],[1491584274653,18,0],[1491843474653,8,0],[1491929874653,1,0],[1492621074653,25,0],[1492707474653,12,0],[1492793874653,2,0],[1501174674653,2,0],[1503593874653,2,2],[1510765074653,1,0],[1510851474653,1,1],[1510937874653,5,0],[1511197074653,7,3],[1511369874653,7,2],[1511542674653,1,0],[1511801874653,7,3],[1511974674653,1,0],[1512493074653,1,1],[1512665874653,2,2],[1512752274653,9,4],[1513184274653,2,2],[1513270674653,2,2],[1513616274653,3,0],[1513789074653,4,2],[1514912274653,1,0],[1515430674653,1,0]]
The array displays timestamp on the xAxis and given recognition on the y axis.
How do I create a stacked column with "received recognition" stacked on "given recognition" on the yAxis?
I have searched google for hours and I can't find an example that uses same json array like mine, without strings as catagories.
I assume I will have to customise series or plotOptions and identify the data columns via the number data[1], data[2]?
How will I achieve a similar column like this CSV column:
http://marialaustsen.com/columncsv.html
HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>myGraph</title>
<!--
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" type="text/css" rel="stylesheet" />
-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" type="text/css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js" integrity="sha256-0YPKAwZP7Mp3ALMRVB2i8GXeEndvCq3eSl/WsAl1Ryk=" crossorigin="anonymous"></script>
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>-->
<!-- Highcharts is already included in Highstock, so it is not necessary to load both. The highstock.js file is included in the package. -->
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<!-- But the separate files can't run in the same page along with each other or with highcharts.js. So if stock or maps are required in the same page as each other or with basic Highcharts, they can be loaded as modules: -->
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="height: 400px; width: 100%"></div>
<script>
$(function() {
console.log($);
$.getJSON('http://localhost:3000/recognition', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart: {
type: 'column',
renderTo: 'container'
},
legend: {
enabled: true,
},
tooltip: {
pointFormat: '<span style="color:{point.color}">\u25CF </span> <b>{point.series.name}: <b>{point.y}</b> ({point.percentage:.1f}%)<br/>',
valueSuffix: ' k',
shared: true,
},
series: [{
name: 'Brands',
data: data
}],
rangeSelector: {
selected: 1,
inputDateFormat: '%Y-%m-%d',
floating: true,
y: -75,
verticalAlign: 'bottom'
},
title: {
text: 'Team members received and sent recognition'
},
navigator: {
margin: 50
},
xAxis: {
type: 'datetime',
title: {
text: 'DATES'
}
},
yAxis: {
title: {
text: 'BRANDS'
}
},
plotOptions: {
column: {
stacking: 'normal'
}
},
}, function(chart) {
// apply the date pickers
setTimeout(function() {
$('input.highcharts-range-selector', $('#' + chart.options.chart.renderTo)).datepicker()
}, 0)
});
});
// Set the datepicker's date format
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd',
onSelect: function(dateText) {
chart.xAxis[0].setExtremes($('input.highcharts-range-selector:eq(0)').datepicker("getDate").getTime(), $('input.highcharts-range-selector:eq(1)').datepicker("getDate").getTime());
//this.onchange();
this.onblur();
}
});
});
</script>
</body>
</html>
You need to prepare your data - split it into 2 separate series:
series: (function() {
var series = [{
name: 'received recognition',
data: []
}, {
name: 'given recognition',
data: []
}];
data.forEach(function(p) {
series[0].data.push([p[0], p[1]]);
series[1].data.push([p[0], p[2]]);
});
return series;
})()
Live demo: http://jsfiddle.net/kkulig/88sr9ofn/

limit amout result from json array for chart.js

How do I get it to limit the amount of existing onject in array JSON using Chart.js?
Suppose I have 120 onbject in a single array, then I want to only display only 10 data in Chart.js. My data exist in the firebase, I tried to use limitToLast=10 , however, does not display any data, and this is my code.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="JS/jquery-3.2.1.min.js"></script>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div class="container" style="width: 90%;">
<canvas id="canvas">
</canvas>
</div>
<script>
$.getJSON("https://skripsi-adeguntoro.firebaseio.com/sensor1.json", function (json) {
console.log(json);
var temp = json.map(function(item) {
return item.temp;
});
var time = json.map(function(item) {
return item.time;
});
var date = json.map(function(item) {
return item.date;
});
console.log(date);
console.log(time);
console.log(temp);
var config = {
type: 'bar',
data: {
labels: time,
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(220,220,220,1)",
borderColor: "rgba(220,200,230,1)",
data: temp,
fill: false,
}]
},
options: {
responsive: true,
title:{
display:true,
text:'Chart.js Line Chart'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Time'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Temperature'
},
ticks: {
beginAtZero: false,
stepSize: 5
}
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
</body>
</html>
Thank for your help.

creating a bar chart using Highcharts with React - getting an error that rendering div isn't found

I'm trying to create a bar chart with Highcharts in my web application, which uses React on the front end. Below is a snippet of my dashboard.tsx file, where I basically just copied and pasted the code from a JSFiddle
(http://jsfiddle.net/8qjcz4q0/)
that renders a simple bar chart with Highcharts, but for some reason it's not working and I get an error in my console (Highcharts error #13) that the rendering div isn't showing.
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as Highcharts from "highcharts";
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'World\'s largest cities per 2014'
},
subtitle: {
text: 'Source: Wikipedia'
},
xAxis: {
type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Population (millions)'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: 'Population in 2008: <b>{point.y:.1f} millions</b>'
},
series: [{
name: 'Population',
data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Istanbul', 14.2],
['Karachi', 14.0],
['Mumbai', 12.5],
['Moscow', 12.1],
['São Paulo', 11.8],
['Beijing', 11.7],
['Guangzhou', 11.1],
['Delhi', 11.1],
['Shenzhen', 10.5],
['Seoul', 10.4],
['Jakarta', 10.0],
['Kinshasa', 9.3],
['Tianjin', 9.3],
['Tokyo', 9.0],
['Cairo', 8.9],
['Dhaka', 8.9],
['Mexico City', 8.9],
['Lima', 8.9]
],
}]
});
render() {
return ( <div>
<div id="container"></div>
</div>
);
}
}
My suspicion is that the HTML id attribute doesn't work with React, but I don't know if Highcharts can render to class instead of id.
To answer my own question here, the render function is called after highcharts attempts to look for the div. You can put the chart rendering code in the componentDidMount() section, render the highcharts code directly using dangerouslySetInnerHTML, or set a timer on the highcharts code.
To the other answer, the problem with sticking the div tag in my html is that I'm rendering everything else in the JSX and thus want to render my chart from inside my JSX.
JS bin demo
Html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/react-highcharts/11.0.0/ReactHighcharts.js"></script>
<meta charset="utf-8">
<title>React-highcharts</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
JS Part
var config = {
chart: {
type: 'column'
},
title: {
text: 'World\'s largest cities per 2014'
},
subtitle: {
text: 'Source: Wikipedia'
},
xAxis: {
type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Population (millions)'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: 'Population in 2008: <b>{point.y:.1f} millions</b>'
},
series: [{
name: 'Population',
data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Istanbul', 14.2],
['Karachi', 14.0],
['Mumbai', 12.5],
['Moscow', 12.1],
['São Paulo', 11.8],
['Beijing', 11.7],
['Guangzhou', 11.1],
['Delhi', 11.1],
['Shenzhen', 10.5],
['Seoul', 10.4],
['Jakarta', 10.0],
['Kinshasa', 9.3],
['Tianjin', 9.3],
['Tokyo', 9.0],
['Cairo', 8.9],
['Dhaka', 8.9],
['Mexico City', 8.9],
['Lima', 8.9]
],
}]
};
ReactDOM.render(
<ReactHighcharts config = {config}/>,
document.getElementById('container')
);

Angular js query not running

I had tried to run the jqgrid using angularjs, but i did not get any output.
I had uses the following:
HTML
<html ng-app="myApp">
<head>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<link data-require="jqgrid#*" data-semver="4.5.2" rel="stylesheet" href="//cdn.jsdelivr.net/jqgrid/4.5.2/css/ui.jqgrid.css" />
<script data-require="jqgrid#*" data-semver="4.5.2" src="//cdn.jsdelivr.net/jqgrid/4.5.2/jquery.jqGrid.js"></script>
<script data-require="angular.js#*" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/redmond/jquery-ui.css" />
<style type="text/css"></style>
<script src="ngtest.js">
</script>
</head>
<body ng-app="myApp" ng-controller="MyController">
<ng-jq-grid config="config" data="data"></ng-jq-grid>
</body>
</html>
Javascript
var myApp = angular.module("myApp", ["ui.bootstrap"]);
myApp.directive("ngJqGrid", function ($compile) {
return {
restrict: "E",
scope: {
config: "=",
data: "="
},
link: function (scope, element, attrs) {
var $grid;
scope.$watch("config", function (newValue) {
element.children().empty();
$grid = angular.element("<table id='" + $.jgrid.jqID() + "'></table>");
element.append($compile($grid)(scope));
element.append($grid);
angular.extend(newValue, {
autoencode: true,
iconSet: "fontAwesome",
cmTemplate: { autoResizable: true },
autoResizing: { compact: true },
autoresizeOnLoad: true,
loadComplete: function () {
$compile(this)(scope);
}
});
angular.element($grid)
.jqGrid(newValue)
.jqGrid("navGrid")
.jqGrid("filterToolbar");
});
scope.$watch("data", function (newValue, oldValue) {
$grid.jqGrid("clearGridData");
$grid.jqGrid("setGridParam", {data: newValue});
$grid.trigger("reloadGrid");
});
}
};
});
myApp.controller("MyController", function ($scope) {
$scope.config = {
myClick: function (rowid) {
alert("Test buton is clicked on rowid=" + rowid);
},
colNames: ["Client", "", "Date", "Closed", "Shipped via", "Amount", "Tax", "Total", "Notes"],
colModel: [
{ name: "name", align: "center", width: 65, editrules: {required: true},
searchoptions: { sopt: ["tcn", "tnc", "teq", "tne", "tbw", "tbn", "tew", "ten"] }},
{ name: "myLink", align: "center",
formatter: function (cellvalue, options, rowObject) {
return "<button class='btn btn-primary' popover-placement='top' popover='" +
rowObject.note + "' ng-click='config.myClick(" + options.rowId + ")'>Test</button>";
}},
{ name: "invdate", width: 125, align: "center", sorttype: "date",
formatter: "date", formatoptions: { newformat: "d-M-Y" },
editoptions: { dataInit: initDateEdit },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch } },
{ name: "closed", width: 70, template: "booleanCheckboxFa" },
{ name: "ship_via", width: 105, align: "center", formatter: "select",
edittype: "select", editoptions: { value: "FE:FedEx;TN:TNT;IN:Intim", defaultValue: "IN" },
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;FE:FedEx;TN:TNT;IN:IN" } },
{ name: "amount", width: 75, template: "number" },
{ name: "tax", width: 52, template: "number", hidden: true },
{ name: "total", width: 60, template: "number" },
{ name: "note", width: 60, sortable: false, edittype: "textarea" }
]
};
$scope.data = [
{ id: "11", invdate: "2007-10-01", name: "test", note: "note", amount: 0, tax: 0, closed: true, ship_via: "TN", total: 0 },
{ id: "21", invdate: "2007-10-02", name: "test2", note: "note2", amount: 351.75, tax: 23.45, closed: false, ship_via: "FE", total: 375.2 },
....etc
];
});
Fiddle
You have a lot of things going on:
You need to load external resources on the left panel when using jsfiddle.
When using jsfiddle you do not include a header it is automatically included in the output
You didn't include the angular-ui-bootstrap javascript files that you have as a dependency
You are using an older version of angular which does not pair with angular-ui-bootstrap, I updated the angular dependency to 1.3.20 to get things to run
When using jsfiddle with angular you need to select No wrap - in <body> from the options on the left or it will not run angular.
You are trying to bind the app to the DOM twice, you only need one ng-app="myApp"
And you have functions you are calling such as initDateEdit and initDateSearch which where not defined
All that being said, making these changes the app will load in jsfiddle.
Working Fiddle

How to add sprite to sencha touch chart

I have sencha donut chart in window panel and text sprite in another panel. but i need to integrate this sprite with donut chart, so that if i will move the chart, the added text sprite will move accordingly.
Here is my code:
Ext.setup({
tabletStartupScreen: 'tablet_startup.jpg',
phoneStartupScreen: 'phone_startup.jpg',
tabletIcon: 'icon-ipad.png',
phoneIcon: 'icon-iphone.png',
glossOnIcon: false,
requires: ['Ext.chart.Panel',
'Ext.chart.axis.Numeric',
'Ext.chart.axis.Category',
'Ext.chart.series.Pie'],
onReady: function () {
var donut = false;
window.initExample('Pie Chart',
"This example's uses many interactions.<br><ul>" +
"<li>Dragging the Pie Chart will rotate it.</li>" +
"<li>Tap and hold will bring up additional information about a slice</li>" +
"<li>Double-Tap will reset the chart back to the initial state (after confirmation)</li>");
window.createPanel(new Ext.chart.Chart({
themeCls: 'pie1',
theme: 'Demo',
store: store1,
shadow: false,
animate: true,
insetPadding: 20,
legend: {
position: 'left'
},
interactions: [
{
type: 'reset',
confirm: true
},
{
type: 'rotate'
},
'itemhighlight',
{
type: 'iteminfo',
gesture: 'longpress',
listeners: {
show: function (interaction, item, panel) {
var storeItem = item.storeItem;
panel.setHtml(['<ul><li><b>Month: </b>' + storeItem.get('name') + '</li>', '<li><b>Value: </b> ' + storeItem.get('2007') + '</li></ul>'].join(''));
}
}
}
],
series: [
{
type: 'pie',
field: '2007',
showInLegend: true,
highlight: false,
donut: 50,
listeners: {
'labelOverflow': function (label, item) {
item.useCallout = true;
}
},
// Example to return as soon as styling arrives for callouts
callouts: {
renderer: function (callout, storeItem) {
callout.label.setAttributes({
text: storeItem.get('name')
}, true);
},
filter: function () {
return false;
},
box: {
//no config here.
},
lines: {
'stroke-width': 2,
offsetFromViz: 20
},
label: {
font: 'italic 14px Arial'
},
styles: {
font: '14px Arial'
}
},
label: {
field: 'name'
}
}
]
}));
mydrawComponent = new Ext.draw.Component({
id:'mydrawComponent',
fill:'blue',
height: '100%',
width: '100%',
fullscreen: true,
items: [{type: 'text',
'text-anchor':'center',
fill: 'black',
font: '20px Arial',
text: 'Investment',
x: 860,
y: 380,
zIndex: 2},
{type: 'text',
'text-anchor':'center',
fill: 'black',
font: 'Bold 30px Arial',
text: '$165m',
x: 860,
y: 410,
zIndex: 3}]
}).show();
new Ext.chart.Panel({
fullscreen: true,
title: 'Text',
items: mydrawComponent
});
}
});
This is the sencha touch donut chart javascript code. and here is the html code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="../CSS/sencha-touch.css" type="text/css">
<link rel="stylesheet" href="../CSS/touch-charts-demo.css" type="text/css">
<title>Donut Chart</title>
<script type="text/javascript" src="../JS/sencha-touch.js"></script>
<script type="text/javascript" src="../JS/touch-charts.js"></script>
<script type="text/javascript" src="../JS/examples.js"></script>
<script type="text/javascript" src="donutchart.js"></script>
</head>
<body></body>
</html>
I was thinking for 2 different approaches:
1) If we can get Donut chart center point X/Y co-ordinates then we can add sprite to that X/Y co-ordinates.
2) We can add panel to the chart and then add drawComponent or sprite to that panel.
Please let me know how we can do this.
Thanks!!

Resources