Google Line Chart Customization - javascript

I have these line charts here with real time data from an arduino.
What i want to do is to make the first graph (Temperature) better looking. I want to have always some gaps from the top and bottom (Like humidity) and i want to increase the width of the Y Axis of temperature. Is this possible ?
Both charts has run with exactly the same settings:
function drawTemperature() {
$.ajax({
url: 'http://192.168.1.3/Charts/chart_temperature.php',
dataType: 'json',
success: function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {
'title': 'Temperature',
'width': 1200,
'height': 600
//'legend.alignment' : 'start',
//'hAxis.baseline' : 5,
//'chartArea.top' : 20,
//'chartArea.left' : 500
//'focusTarget' : 'category'
//'animation.easing' : 'inAndOut'
//colors:['blue','#004411'],
//'hAxis.maxValue' : 30,
//'hAxis.showTextEvery' : 0.1,
//'hAxis.logScale' : 'true',
//'hAxis.gridlines.color' : '#00CC00',
//'hAxis.maxAlternation' : 10,
//'hAxis.viewWindow.max' : 10
//'curveType': 'function'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_temperature'));
chart.draw(data, options);
}
});
}
function drawHumidity() {
$.ajax({
url: 'http://192.168.1.3/Charts/chart_humidity.php',
dataType: 'json',
success: function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_humidity'));
chart.draw(data, {width: 1200, height: 600});
}
});
}
function drawVisualization() {
drawTemperature();
drawHumidity();
}

You can create "gaps" at the top and bottom of you chart by setting the vAxis.minValue and vAxis.maxValue options to values less than the minimum and maximum (respectively) of your chart's data. Here's one way you might do this:
var range = data.getColumnRange(1);
var options = {
title: 'Temperature',
width: 1200,
height: 600,
vAxis: {
minValue: range.min - 1,
maxValue: range.max + 1
}
};

Related

How can I limit my Google chart to 7 items?

I'm wondering how I could limit the MAX amount of items it can display to my chart to 5. I've got a cron job updating the .json daily, and currently it just tries to fit them all onto there.
This is my code:
<script>
google.charts.load("visualization", "1", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/server/database.json",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Players Hourly',
'is3D':true,
legend: 'bottom',
hAxis: {
minValue: 0,
format: 'long'
},
vAxis: {
minValue: 0,
scaleType: 'log',
format: 'long'
},
pointSize: 5,
series: {
0: { pointShape: 'circle' },
}
};
var chart = new google.visualization.LineChart(document.getElementById('serverstats'));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
</script>
Thank you.
an easy way would be to use a data view and the setRows method.
then use the view to draw the chart.
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setRows([0, 1, 2, 3, 4]); //<-- provide an array of the row indexes you want to see
...
chart.draw(view, options); //<-- use view here
EDIT
to show the last 5 rows...
var viewRows = [];
for (var i = data.getNumberOfRows() - 1; i > data.getNumberOfRows() - 6; i--) {
viewRows.push(i);
}
view.setRows(viewRows);

Highchart ID does not update with new variable

I try to generate a windrose on my website using highcharts. It should display the direction with an arrow and the speed in the gauge itself.
I have the following code to generate the charts:
$(document).ready(function() {
var chart = new Highcharts.Chart({
\\ some other parameters not relating to question
series: [{
data: [{
id: 'wnddr',
y: winddir,
dial: {
radius: '90%',
baseWidth: 3,
baseLength: '95%',
rearLength: 0
}
}],
dataLabels: {
enabled: true,
formatter : function(){
return windspd + ' km/u';
}
}
}]
},
function (chart){
setInterval(function() {
$.ajax({
type: "POST",
url: "example.php",
dataType: "JSON",
cahce: "false",
success: function(data){
windspd = data.query.results.channel.wind.speed;
winddir = data.query.results.channel.wind.direction;
windchill = data.query.results.channel.wind.chill;
hum = data.query.results.channel.atmosphere.humidity;
druk = data.query.results.channel.atmosphere.pressure;
ss = data.query.results.channel.astronomy.sunset;
sr = data.query.results.channel.astronomy.sunrise;
temp = data.query.results.channel.item.condition.temp;
des = data.query.results.channel.item.forecast[0].code;
var point = chart.series[0].points[0];
point.update(winddir);
// alert(winddir);
}
});
$('.update').html("<img src=http://l.yimg.com/a/i/us/we/52/" +des+ ".gif />");
}, 5000);
});
});
With wnddr.update(winddir); I was trying to update the winddir-variable in my chart. However, I can't get it to work. Also the alert does not pop-up so probably my code gets stuck just before. If I comment the two line above the alert out, the alert will work. Same goes for the speed-variable. Problem here is that is doesn't have a id-attribute.
I modified the code from highcharts as the basis. Giving 'y' a value by hand generates a valid and correct gauge. The same goes for a fixed value of winddir.

Paging google charts stacked column chart

I searched quite a bit for this, but haven't found what I'm looking for.
I'm building a stacked column chart using google charts, and I have over 200 rows. I want to page the results, but I haven't been able to accomplish it. Is it possible to page rows with a stacked column chart ? Here's my current code:
google.load('visualization', '1', {'callback':'drawChart', 'packages':['corechart']});
function drawChart() {
var jsonData = $.ajax({
type: 'GET',
url: "dashboard/lead/by-month",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(
jsonData
);
var options = {
width: 900,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true,
showRowNumber: true,
page: 'enable',
pageSize: 10,
sortColumn: 3,
sortAscending: false
};
var chart = new google.visualization.ColumnChart(document.getElementById("chartContainer"));
chart.draw(data, options);
};
You can do with external paging like, first you fetch 10 records from database and load the chart, after that same way you can call another 10 records with paging and load chart and so on.
The idea is to load chart with every call you make for to fetch records.

Google pie chart shows opposite colors

I have a pie chart that looks like this in the javascript:
function drawCurrentPieChart(title,days) {
var name = document.getElementById("dropdownSubCategories").value;
$
.ajax({
url : "piechartlist/",
type : "GET",
aync : true,
dataType : "json",
data : {days:days,
categoryName : name + ""},
error : function(e) {
alert(e.message + "ERROR ");
},
success : function(response) {
var jsonData = response;
if (response == "") {
alert("Error: Threshold is not valid or there is no status in the database within 24 hours.");
} else {
var data = [["Count","Color"]], colors = [];
for(var c in jsonData){
data[data.length] = [jsonData[c]["color"],jsonData[c]["count"]];
colors[colors.length] = jsonData[c]["color"];
}
data = google.visualization.arrayToDataTable(data);
var options = {
title: title,
'chartArea': {'width': '100%', 'height': '80%'},
'legend': {'position': 'bottom'},
backgroundColor: 'transparent',
colors : colors
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'+days));
chart.draw(data, options);
}
}
});
When it draws the chart, it shows the opposite colors that it recieves from the database (green is red, red is green etc.) What can be the problem?

HighChart flags Data load issues

I am working on drawing graphs from our data. There is no problem on drawing graph basically. The only problem is that the flags information is not loaded and located on the graph lines. Let me give you the issues on it.
Data cannot be brought to the graph if it has over 900 numbers of items.
One data might have more than 4000 items.
Instead using one big data, I tried to spilt one data into small pieces of data. Each piece of data has 800 items, and they are intended being loaded on the graph sequentially. However, this process was not easily done well. Sometime the graph module cannot load every piece exactly. Moreover, this process take much time than using one data.
I wonder whether an appropriate way to load flag data which contains many items exits or not.
$(function() {
var report_data;
$.ajax({
type: "post",
url:"/apps.chart/chart.reportShort",
data:"callback=?&report_type=CO&business_code=005930",
dataType:"json",
success:function(report){
report_data = report;
}
});
$.getJSON('/apps.chart/chart.chartList?callback=?&report_type=CO&business_code=005930', function(data) {
// Create the chart
$('#chartView').highcharts('StockChart', {
chart: {
plotBorderColor: '#346691',
plotBorderWidth: 2,
height: 600
},
rangeSelector : {
inputEnabled: $('#chartView').width() > 400,
selected : 1
},
title : {
text : 'SK'
},
tooltip: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%Y년 %m월 %d일'
},
style: {
width: '300px'
},
valueDecimals: 0
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%m.%d',
week: '%m.%d',
month: '%Y.%m',
year: '%Y'
}
},
yAxis : {
labels : {
formatter : function() {
var n = this.value;
var reg = /(^[+-]?\d+)(\d{3})/;
n += '';
while (reg.test(n))
n = n.replace(reg, '$1' + ',' + '$2');
return n;
},
align : 'left',
x : 5,
y : 2
},
maxPadding: 0.2,
minPadding: 0,
minorTickInterval: 'auto',
title : {
text : '금액(원)',
}
},
series : [{
name : '종가',
data : data,
id : 'dataseries',
marker : {
enabled : true,
radius : 3
},
shadow : true,
tooltip : {
valueDecimals : 0
}
}
// the event marker flags
,{
type : 'flags',
data : report_data,
style: {
cursor: 'hand'
},
onSeries : 'dataseries',
shape : 'circlepin',
width : 15,
height : 15,
color : '#121212'
}
]
});
});
});
Probably the problem is that you call two ajax asynchronously, so I advice you to next ajax insiae first callback and then initialise chart.

Categories