I am trying to display data using Google's Column chart. I tried displaying bars not stacked but it would not display one bar from both ends. Then i changed the property isStacked to true, it displays all the bars but it crops the bar at the both ends.
How can i fix this issue?
I was playing around with the options but nothing seems to work.
<script type='text/javascript'>
google.load('visualization', '1', { 'packages': ['corechart'] });
google.setOnLoadCallback(drawSizeChart);
var d = 0;
function drawSizeChart() {
$.post('/metrics/SiteResourceChart', { fnsId: "#Model.FnsId", regionId: selectedValue },
function (data) {
if (Object.keys(data).length !== 0) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('date', 'Date');
for (var p = 0; p < data.length; ++p) {
tdata.addColumn('number', data[p][0].PathName);
}
d = data[0].length;
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
var date = new Date(parseInt(data[i][j].CreatedAt.substr(6)));
var rCount = data[i][j].ResourceCount;
if (i === 0)
tdata.addRow([date, rCount, null]);
else
tdata.addRow([date, null, rCount]);
}
}
var options = {
title: 'Resource Count',
titleTextStyle: { fontSize: 20 },
isStacked: true,
bar: { groupWidth: '20%' },
chartArea: { left: '50' },
hAxis: { viewWindowMode: 'maximized' }
//legend: { position: 'none' }
};
var chart = new google.visualization.ColumnChart(document.getElementById('site_size_chart'));
chart.draw(tdata, options);
}
}
);
}
</script>
I guess a quick solution would be to define your first column as 'string' instead of Date and leave the hAxis.viewWindowMode as default. Otherwise, you should configure hAxis.viewWindow object (i.e., min/max values).
Same issue here. What I did is that I added dummy data with a 0 value one day before the first date and one day after the last date in order to achieve the desired result.
Using the columnchart package wasn't a solution for me because I had days without data but wanted to keep the time axis proportional.
Related
I have a chart to represent some temperatures of a specific place, I am using Google Chart tools (area chart), and Im trying to put a diferent color (orange) if the temperature is greater than 25 degrees
Javascript code
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Data');
data.addColumn('number', 'Temperatura ºC');
data.addColumn({ type: 'number', role: 'annotation' });
var array = JSON.parse('<%=jsonStringTemp%>');
console.log(array);
for(var i=0; i<array.length;i++){
var array2=[];
for (j = 0; j < array[i].length; j++){
if (typeof array[i][j]==='string') {
if (j !== 0) {
array[i][j]=parseInt(array[i][j], 10)
}
}
array2.push(array[i][j])
}
data.addRow(array2)
}
console.log(data)
var options = {
title: 'Temperatura',
hAxis: {title: 'Data', titleTextStyle: {color: '#333'}},
vAxis: { minValue: 0 },
series: {
0: {
color: 'green'
},
},
pointSize: 6
};
;
var chart = new google.visualization.AreaChart(document.getElementById('linechart_material'));
chart.draw(data, options);
}
output
Is it possible to do it? And How?
I am displaying a chart using Google API and I am getting a chart but it is not displaying that line in the graph,
This is the code I am trying with, I am using array data for charts,
var jsonlength = data.feed.entry.length;
var timestamp = new Array(jsonlength);
var temperature = new Array(jsonlength);
var tempid = new Array(jsonlength);
for (var i = 0; i < jsonlength; i++) {
timestamp[i] = ((data.feed.entry[i].gsx$timestamp.$t));
temperature[i] = ((data.feed.entry[i].gsx$temperaturevalue.$t));
}
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
for (var i = 0; i < jsonlength; i++) {
console.log(i);
data1.addRows(i,data.feed.entry[i].gsx$temperaturevalue.$t);
//Here I can display all those values, But still not getting the chart, Though I have given proper values, Help me here
console.log(data.feed.entry[i].gsx$temperaturevalue.$t);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Temperature'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data1, options);
This is the output I am getting without a line, Please help me I am new to this
Output without a line in the graph
most likely is due to 'string' values vs. number
try this...
temperature[i] = (parseFloat(data.feed.entry[i].gsx$temperaturevalue.$t));
here...
for (var i = 0; i < jsonlength; i++) {
timestamp[i] = ((data.feed.entry[i].gsx$timestamp.$t));
temperature[i] = (parseFloat(data.feed.entry[i].gsx$temperaturevalue.$t));
}
EDIT
here, you create data
var data = new google.visualization.DataTable();
but then you're adding columns to data1 ???
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
try syncing up the variable names and check addRow below...
var data1 = new google.visualization.DataTable();
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
for (var i = 0; i < jsonlength; i++) {
// use addRow -- which takes an array
data1.addRow([i,data.feed.entry[i].gsx$temperaturevalue.$t]);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Temperature'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data1, options);
I used this ,to multiply doughnut chart according as array(arr) has,but it can't change to object,(data has string type).So chart doesn't appear here..,how fix it
var arr=['HTML','CSS','JS'],i,data;
data ='[';
for(i=0;i<arr.length;i++){
if(i==arr.length-1){
data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]}';
}
else{
data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]},';
}
}
data += ']';
var dat = data;
window.onload = function () {
var ctx = document.getElementById("chart-area").getContext("2d");
window.myBar = new Chart(ctx).Doughnut(dat,{
responsive: true,
});
};
//want like this
dat =[{value:"300",color:"#fff",highlight:"#aaa",label:"HTML"},
{value:"200",color:"#fff",highlight:"#aaa",label:"CSS"}];
You are creating your array as a String.
You need to create an array of objects [{},{},{}].
The method used to INSERT a new object in an array is PUSH().
Check the fiddle. Now it´s working OK (move the mouse on the screen to see the chart is there (you will only see it when mouse is over it):
window.onload = function() {
var arr = ['HTML', 'CSS', 'JS'],
i, data;
data = [];
for (i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
data.push({
value: "300",
color: "#fff",
highlight: "#aaa",
label: arr[i]
});
} else {
data.push({
value: "300",
color: "#fff",
highlight: "#aaa",
label: arr[i]
});
}
}
var dat = data;
var ctx = document.getElementById("chart-area").getContext("2d");
window.myBar = new Chart(ctx).Doughnut(dat, {
responsive: true,
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/nnnick/Chart.js/master/Chart.js"></script>
<canvas id="chart-area"></canvas>
I am working with jquery HighCharts. I want to create a common function to develop multiple charts of same type.
To achieve this goad I created a function as follow -
function generateGraph(data) {
var dates = new Array();
var startDate = "";
for (var i = 0; i < data.length; i++) {
dates[i] = data[i].date;
}
var productInsight = _comm.getProductInsightArray();
var productInsight_Array = new Array();
$.each(productInsight, function(key, value) {
productInsight_Array.push(key);
});
if(dates.length > 0) {
startDate = dates[0].split("/");
}
intervals = 24 *3600 * 1000; //one day
var title = $("#DateSearch_analytics_Similar_Stores1").val();
var color = ['#000000', '#FFFFFF', '#000080', '#0000FF', '#808080'];
var containers =['container1', 'container2','container3','container4', 'container5', 'container6', 'container7', 'container8', 'container9'];
for(var j=0; j<containers.length; j++)
{
var chart = new Highcharts.Chart({
chart: {
zoomType: 'x',
renderTo: containers[j],
type: 'line',
},
title: {
text: title
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' :
'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime',
tickInterval: intervals,
},
series: []
});
for(var i=0; i < productInsight_Array.length; i++) {
var fillData = new Array();
var counter = 0;
var productValue = document.getElementById('product-nm').value;
$.each(dates, function() {
fillData[counter] = _comm.randomNumberFromRange(_randomNumberStartRange, _randomNumberEndRange);
counter++;
});
chart.addSeries({
name: productInsight_Array[i],
type: 'line',
color: color[i],
pointStart: Date.UTC(startDate[2], startDate[0] - 1, startDate[1]),
pointInterval: intervals,
data: fillData,
});
}
$("text:contains('Highcharts.com')").css("display", "none");
}
}
Its working fine and developing charts on window load and button click. I am saving these graph in 9 container but this script is not loading graph in 3rd container and when I remove 3rd container than its not loading in fourth and so on. But it works fine when I call this function on button click in place of document load.
I am little surprised why its happing, As a common function creting all graphs.
I need your help! :(
Thanks
The problem is when load the function your markup doesnt exists. For this reason when you click the button works ok. When the button is visible, all markup is already loaded.
Review your load order.
Also aside comment: put this in your chart declaration:
credits: {
enabled: false
}
To not show the credits message: "Highcharts.com".
An example
I'm trying to replicate the following code from a working example:
series: {0: {targetAxisIndex:0},
1: {targetAxisIndex:0},
2: {targetAxisIndex:1},
This is for setting which y-axis is used to plot different columns from a dataTable on a Google chart.
However I have a variable number of columns (based on user input), therefore am collecting an array of the required axis (the axisAssignment Array in the below example).
My code is below:
var series = {};
for (i=0;i<axisAssignment.length;i++)
{
series[i] = {targetAxisIndex: axisAssignment[i]};
}
return series;
However, all of my data is only being written to the left axis, despite the debugger suggesting that the object is correct. My option code is below:
var options =
{
hAxis: {title: xTitle},
vAxes: {0: {title: y1Type},
1: {title: y2Type}
},
series: calculateSeries(),
pointSize: 1,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
Any assistance would be greatly apreciated.
Thanks
Tom
edit: whole file for reference (it's a work in progress so a bit of a mess I'm afraid)
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart());
function drawChart()
{
var title = "Node: "+currentNode;
var xTitle = "Date";
var yTitle = titles[currentVariable];
if (totalData !== null)
{
var tempData = newData();
var tempData2 = totalData;
dataArray[dataCount] = tempData;
var joinMark = countArray(dataCount);
totalData = google.visualization.data.join(tempData2,tempData,'full',[[0,0]],joinMark,[1]);
dataCount = dataCount+1;
}
else
{
totalData = newData();
dataArray[dataCount] = totalData;
dataCount = 1;
}
var options =
{
hAxis: {title: xTitle},
vAxes: {0: {title: y1Type},
1: {title: y2Type}
},
series: calculateSeries(),
pointSize: 0.5,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
var chart = new google.visualization.ScatterChart(document.getElementById('graph'));
console.log(calculateSeries());
chart.draw(totalData, options);
function countArray(count)
{
var arrayCount= new Array();
if (count===1)
{
arrayCount[0] = count;
}
else
{
for (var i=0;i<count;i++)
{
var temp = i+1;
arrayCount[i] = temp;
}
}
return arrayCount;
}
function calculateSeries()
{
var series = {};
for (i=0;i<axisAssignment.length;i++)
{
series[i] = {targetAxisIndex: axisAssignment[i]};
}
return series;
}
function newData()
{
var dataType = dataIn[0];
dataIn.shift();
var axis = dataSelect(dataType);
axisAssignment.push(axis);
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', "Node: "+currentNode+": "+titles[currentVariable]);
var num = (dataIn.length);
data.addRows(num/2);
var i = 0;
var j = 0;
while (i<num)
{
var d = (dataIn[i]);
if (i%2===0)
{
d = new Date(d);
data.setCell(j,0,d);
i++;
}
else
{
data.setCell(j,1,parseFloat(d));
i++;
j++;
}
}
return data;
}
function dataSelect(type)
{
var axisNumber;
if (y1Type === null || y1Type === type)
{
y1Type = type;
axisNumber = 0;
}
else if (y2Type === null || y2Type === type)
{
y2Type = type;
axisNumber = 1;
}
else
{
alert("You already have 2 axes assigned.\n\nPlease clear the graph \nor select more objects of \ntype"+y1Type+" or \ntype "+y2Type+" to continue.");
axisNumber = null;
}
return axisNumber;
}
}
Ok, it seems that it's an issue with my choice of ScatterChart,
var options =
{
hAxis: {title: xTitle},
series: calculateSeries(),
vAxes: {0: {title: y1Type },
1: {title: y2Type}
},
pointSize: 0.5,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
var chart = new google.visualization.LineChart(document.getElementById('graph'));
chart.draw(totalData, options);
I've changed it to LineChart and it's working fine, by keeping the pointSize option, the appearance is almost completely unchanged. Thanks for your help juvian.