Plotting json on .JS - javascript

I am trying to plot some json data but for some reason code is not workingLet me show my code.
My json looks like this:
{"d1":[[1356912000000, 1],[1356825600000, 1],[1356739200000, 1],[1356652800000, 1],[1356566400000, 38],[1356480000000, 47],[1356393600000, 1],[1356307200000, 4],[1356220800000, 1],[1356134400000, 2],[1356048000000, 50],[1355961600000, 51],[1327017600000, 38],[1326931200000, 52],[1326844800000, 45],[1326758400000, 49],[1326672000000, 46],[1326585600000, 1],[1326499200000, 5],[1326412800000, 44],[1326326400000, 48],[1326240000000, 43],[1326153600000, 46],[1326067200000, 41],[1325980800000, 1],[1325894400000, 4],[1325808000000, 45],[1325721600000, 43],[1325635200000, 42],[1325548800000, 42],[1325462400000, 43]]}
I am trying to plot with following code:
$(document).ready(function () {dashboard_A_chart.chartVisit ();});
dashboard_A_chart = {
chartVisit: function () {
var elem = $('#dashChartVisitors');
var options = {
colors: ["#edc240", "#5EB95E"],
legend: {
show: true,
noColumns: 2,
labelFormatter: null,
labelBoxBorderColor: false,
container: null,
margin: 8,
backgroundColor: false
},
xaxis: {
mode: "time",
font: {
weight: "bold"
},
color: "#D6D8DB",
tickColor: "rgba(237,194,64,0.25)",
min: "1325462400000",
max: "1356912000000",
tickLength: 5
},
selection: {
mode: "x"
},
};
var d1 = []
function onDataReceived(series) {d1 = [ series ];$.plot(elem, d1, options);}
$.ajax({
url: "../giga/data/dados1.json",
method: 'GET',
dataType: 'json',
success: onDataReceived
});
},
};

you are trying to call dashboard_A_chart.chartVisit() which is a function of an object literal which needs to be defined before.
you are creating the elem and options var inside the inside the chartVisit-function, but trying to use it in your onDataReceived-Function where it is not present.
it pretty much looks like you just copy & pasted some stuff together. take a looke at this code, that should work:
$(document).ready(function () {
var elem = $('#dashChartVisitors');
var options = {
colors: ["#edc240", "#5EB95E"],
legend: {
show: true,
noColumns: 2,
labelFormatter: null,
labelBoxBorderColor: false,
container: null,
margin: 8,
backgroundColor: false
},
xaxis: {
mode: "time",
font: {
weight: "bold"
},
color: "#D6D8DB",
tickColor: "rgba(237,194,64,0.25)",
min: "1325462400000",
max: "1356912000000",
tickLength: 5
},
selection: {
mode: "x"
}
};
$.ajax({
url: "../giga/data/dados1.json",
method: 'GET',
dataType: 'json',
success: function (data) {
$.plot(elem, data, options);
}
});
});

Related

chart.js display a default chart with option value

so I'm generating charts with a database and displaying them with JSON script and it works fine but the chart only displays when I click an option value, what I'm trying to do now is set a default value option for when the website opens it displays a default chart if that makes sense, below is my chart.js code.
function renderHtmlChart(){
$(document).ready(function (){
var selection= document.getElementById('YEAR').value;
var link = "https://udon.ads.ntu.ac.uk/web/itec30151/N0773065/new/data.php?YEAR='"+selection+"'";
$.ajax({
url: link,
method: "GET",
success: function(data=this.responseText) {
console.log(data);
var Destination = [];
var Bookings = [];
for(var i in data) {
Destination.push(data[i].Destination);
Bookings.push(data[i].Bookings);
}
createChart(Destination,Bookings,selection)
},
error: function(data) {
console.log(data);
}
});
});
}
function createChart(Destination,Bookings,selection){
var universalOptions = {
maintainAspectRatio: true,
responsive: false,
title: {
display: true,
text: 'Top 5 Flight Bookings'
},
legend: {
display: true,
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
scaleLabel: {
display: true,
labelString: 'Bookings'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Destinations'
}
}],
}
}
var chartdata = {
labels: Destination,
datasets : [
{
label: selection,
data: Bookings,
backgroundColor: ["#3366cc","#dc3912","#ff9900","#109618","#990099"],
borderWidth: '1',
borderColour: 'grey',
hoverBorderColor: 'black',
fill: false,
pointRadius: 0,
}
]
};
//stop overlap
$('select').on('change',function(){
barGraph.destroy();
});
// this makes legend hidden
var update_caption = function(legend) {
labels[legend.text] = legend.hidden;
var selected = Object.keys(labels).filter(function(key) {
return labels[key];
});
};
//this creates new graph
var ctx = document.getElementById('myChart');
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: universalOptions,
responsive: false,
});
}
hope you have latest version of jquery like:-
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
hope this will help
//create renderHtmlChart function
function renderHtmlChart()
{
var selection= document.getElementById('YEAR').value;
var link = "https://udon.ads.ntu.ac.uk/web/itec30151/N0773065/new/data.php?YEAR='"+selection+"'";
$.ajax({
url: link,
method: "GET",
success: function(data=this.responseText)
{
console.log(data);
var Destination = [];
var Bookings = [];
for(var i in data)
{
Destination.push(data[i].Destination);
Bookings.push(data[i].Bookings);
}
createChart(Destination,Bookings,selection)
},
error: function(data)
{
console.log(data);
}
});
}
//create createChart function
function createChart(Destination,Bookings,selection)
{
var universalOptions =
{
maintainAspectRatio: true,
responsive: false,
title:
{
display: true,
text: 'Top 5 Flight Bookings'
},
legend:
{
display: true,
},
scales:
{
yAxes: [{
ticks: {
beginAtZero: true,
},
scaleLabel: {
display: true,
labelString: 'Bookings'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Destinations'
}
}],
}
}
var chartdata = {
labels: Destination,
datasets : [
{
label: selection,
data: Bookings,
backgroundColor: ["#3366cc","#dc3912","#ff9900","#109618","#990099"],
borderWidth: '1',
borderColour: 'grey',
hoverBorderColor: 'black',
fill: false,
pointRadius: 0,
}
]
};
// this makes legend hidden
var update_caption = function(legend) {
labels[legend.text] = legend.hidden;
var selected = Object.keys(labels).filter(function(key) {
return labels[key];
});
};
//this creates new graph
var ctx = document.getElementById('myChart');
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: universalOptions,
responsive: false,
});
}
$(funtion(){
//onload call renderHtmlChart function
renderHtmlChart();
//on select input change call renderHtmlChart function
$('select').on('change',function(){
renderHtmlChart();
});
})

how to show mutipal dynamic highcharts based on json data

I want to use json data to construct mutipal pie charts. And put the pie chart inside class container, so for example:
data.data[0].usedPercentage=0,
data.data[1].usedPercentage=20,
data.data[2].usedPercentage=0,
the output pie chart should display like 0%, 20%, 0% ,
but now they display the same all in 0%, could anybody give some clues about that? Thanks a lot
$.ajax({
type: "GET",
url: 'http://XXX.XXX.XXX.XX',
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data);
var used = new Array();
for (var i = 0; i < data.data.length; i++) {
used[i]=data.data[i].usedPercentage;
pieIndex(used[i]);
projectList +="<div class='container'>pie</div>"
function pieIndex(used){
$(function () {
// Using classes to select multiple containers
var $containers = $(".container");
// You just set the configuration object once
var chartConfig = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
name: 'precentage',
colorByPoint: true,
data: [{
name: 'Unused',
y: 100-Number(used),
color: '#eeeeee',
sliced: true,
selected: true
}, {
name: 'Used',
y: Number(used),
color: '#f34s12',
selected: true
}]
}]
};
$containers.each(function() {
$(this).highcharts(chartConfig);
});
});
}
},
error:function(){
alert("connection error");
}
});
});
Each chart need a unique id on the container. Looks like you are overwriting those containers with the last chart. Try using a different id on each container div. For example:
projectList +="<div id='pie-chart-container-" + i + "' class='container'>pie</div>"

Flot not parsing json as categorical data

I am having trouble parsing data into a flot chart. I am unsure if it is the way I am using $.each to build my data arrays. I figured I could Anyone know what's wrong?
UPDATED: correct link:
http://jsfiddle.net/qxdgrozs/
This is my json object and js code:
$(function () {
var jsonString = JSON.parse(readJSON('[
{
"Person":"Fred",
"NetIncome":0,
"StateTax":0,
"FedTax":0,
"TotalTax":0,
"AvgTaxRate":0
},
{
"Person":"Alex",
"NetIncome":5555385.06,
"StateTax":124463.24,
"FedTax":4320151.7,
"TotalTax":4444614.94,
"AvgTaxRate":44.45
},
{
"Person":"John",
"NetIncome":5555180.86,
"StateTax":124667.44,
"FedTax":4320151.7,
"TotalTax":4444819.14,
"AvgTaxRate":44.45
}
]';
var myData = JSON.parse(jsonString);
var data1 = [];
var data2 = [];
$.each(myData, function(i, jti) {
data1[i] = {
label: jti.Person,
data: jti.StateTax
}
data2[i] = {
label: jti.Person,
data: jti.FedTax
}
}
$.plot("#placeholder", [{
data: data1,
label: "test",
bars: {
show: true,
barWidth: 0.4,
align: "left"
}
}, {
data: data2,
label: "flot bug serie",
bars: {
show: true,
barWidth: 0.4,
align: "right"
}
}], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
},
grid: { hoverable: true, clickable: true }
});
});
I have also tired using the push method with no avail.
After fixing a lot of syntax errors, the big issue is that flot needs one array per datapoint, not an object, change
$.each(myData, function(i, jti) {
data1[i] = {
label: jti.Person,
data: jti.StateTax
}
data2[i] = {
label: jti.Person,
data: jti.FedTax
}
}
to
$.each(myData, function(i, jti) {
data1.push([jti.Person, jti.StateTax]);
data2.push([jti.Person, jti.FedTax]);
});
See this fiddle for the working code.

HighCharts dont get value

I try to see temperature history from sqlite database, but i don't get value from server side. I use node.js, socket.io and HighCharts library. I think, its client side problem. Server side:
io.sockets.on('connection', function(socket){
setInterval(function(){
var current_temp = db.all("SELECT * FROM (SELECT * FROM temp_irasai WHERE laikas ORDER BY laikas);",
function(err, rows){
if (err){
console.log('Error serving querying database. ' + err);
return;
}
data = {temp_irasai:[rows]};
socket.emit('istorija', data);
});
}, 5000);
});
Client side:
<script type="text/javascript">
var socket = io.connect('http://ip:3000');
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
zoomType: 'x',
spaceRight: 20,
events: {
load: function (){
socket.on('istorija', function(data){
var series = chart.series[0];
var i = 0;
while (data.temp_irasai[0][i])
{
series.data.push([data.temp_irasai[0][i].laikas, data.temp_irasai[0][i].laipsnis]);
i++;
}
chart.addSeries(series);
});
}
}
},
title: {
text: 'Temperatūra'
},
subtitle: {
text: 'Norint priartinti paspauskite ant grafiko ir pažymekite norimą plotą',
align: 'right',
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000,
title: {
text: 'Time',
margin: 15
}},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
showFirstLabel: false,
title: {
text: 'Temperatūra \u00B0C',
margin: 15
}},
plotOptions: {
area: {
fillColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, 'rgba(2,0,0,0)'],
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 5
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
},
},
series: [{
name: 'DS18B20 jutiklis (\u00B10.5\u00B0C)',
type: 'area',
data: []
}]
});
});
</script>
and database example:
CREATE TABLE temp_irasai(laikas integer PRIMARY KEY, laipsnis real);
INSERT INTO "temp_irasai" VALUES(1399533644551,20.4);
INSERT INTO "temp_irasai" VALUES(1399533646507,20.4);
INSERT INTO "temp_irasai" VALUES(1399533646547,20.4);
INSERT INTO "temp_irasai" VALUES(1399542709224,21.5);
COMMIT;
This part is just wrong:
load: function () {
socket.on('istorija', function (data) {
var series = chart.series[0];
var i = 0;
while (data.temp_irasai[0][i]) {
series.data.push([data.temp_irasai[0][i].laikas, data.temp_irasai[0][i].laipsnis]);
i++;
}
chart.addSeries(series);
});
}
You should add points, or use setData, like this:
load: function () {
socket.on('istorija', function (data) {
var series = chart.series[0];
var i = 0;
var d = [];
while (data.temp_irasai[0][i]) {
d.push([data.temp_irasai[0][i].laikas, data.temp_irasai[0][i].laipsnis]);
i++;
}
series.setData(d);
});
}
There is no data is given in your series set your values data in it, it will loads highcharts for sure, Good Luck!
type: 'area',
data: []
add Series data here.

Redraw JQplot bar chart with new data and tick labels

My code successfully draws a chart with data and tick labels retrieved as JSON object from PHP. Now at one point i want to refresh the chart but with slightly different data and different tick labels without creating a new chart.
$.jqplot.config.enablePlugins = true;
var freqs1 = [];
var freqlabels1 = [];
var dataRendered1 = $.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
if (data.length) {
freqs1 = data[0];
freqlabels1 = data[1];
}
}
});
var plot1 = $.jqplot('chartdiv', [freqs1], {
animate: !$.jqplot.use_excanvas,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
pointLabels: {
show: true
},
rendererOptions: {
barWidth: 12
}
},
title:'Test',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: freqlabels1,
label: "Test 1",
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
},
yaxis: {
label: "Test 2",
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
}
},
highlighter: { show: true }
});
now when button is clicked lets say I have an ajax call that gets the new data and tick labels
$(document).on('click', '#refresh_new', function() {
$.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
var newData = data[0];
var newTicks = data[1];
//HOW DO I REFRESH CHART WITH NEW DATA AND TICKS FOR x-AXIS
}
});
});

Categories

Resources