Google stacked bar chart with date on x and time on y - javascript

Im trying to create a Google stacked bar chart with time on the y-axis and date on x - axis, with no success.
Ex: for 2012-05-01 i want a bar that goes from 00:00 to 24:00.
I have been able to create a simple stacked bar chart like this.
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Austria', 'Bulgaria', 'Denmark', 'Greece'],
['2003', 1336060, 400361, 1001582, 997974],
['2004', 1538156, 366849, 1119450, 941795],
['2005', 1576579, 440514, 993360, 930593],
['2006', 1600652, 434552, 1004163, 897127],
['2007', 1968113, 393032, 979198, 1080887],
['2008', 1901067, 517206, 916965, 1056036]
]);
// Create and draw the visualization.
new google.visualization.BarChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
vAxis: {title: "Year"},
hAxis: {title: "Cups"},
isStacked: true}
);
}
What i'm trying to accomplish is something like this
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('string', 'Name');
data.addColumn('timeofday','Starttime');
data.addColumn('timeofday','Endtime');
data.addRows{
['2015-01-01','Funtime',[13,0,0],[16,0,0],
['2015-01-01','Boringtime',[16,0,0],[19,0,0],
['2015-01-02','Sleeptime',[1,0,0],[5,0,0],
}
The result of this would be two bars. At 2015-01-01 with two events one starting from 13:00 to 16:00 (in the y-axis) and on top of that another from 16:00 to 19:00. On 2015-01-02 there would also be one event from 1:00 to 5:00.
Am I able to do this with Google Bar charts?
Appreciate any help I can get.

there are a few problems in your code, you can check the browser's console for these errors
1.
the addRows method takes an array [] of rows,
and should be called with parenthesis () not curly braces {}
within the array, there should be another array for each row
the rows from the example are not complete and are missing the final bracket ]
['2015-01-01','Funtime',[13,0,0],[16,0,0],
should be
['2015-01-01','Funtime',[13,0,0],[16,0,0]],
2.
the data format does not allow a string column, after the first column
'Funtime' will have to go...
3.
if using type 'date' for the first column, then need actual date objects in the data
if --> data.addColumn('date', 'Date');
use --> [new Date('01/01/2016'), [13,0,0], [3,0,0]],
or a 'string' column can be used for the first column as well
if --> data.addColumn('string', 'Date');
use --> ['2015-01-01', [13,0,0], [3,0,0]],
4.
notice the date format used in this example --> '01/01/2016'
using '2016-01-01' with actual dates will result in problems such as these...
Google Charts Table displaying incorrect date
How do I align date and values to gridlines in Google Chart?
5.
finally, if you want time on the y-axis and date on x - axis
use ColumnChart instead of BarChart
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('timeofday','Starttime');
data.addColumn('timeofday','Endtime');
data.addRows([
[new Date('01/01/2016'), [13,0,0], [3,0,0]],
[new Date('01/02/2016'), [16,0,0], [3,0,0]],
[new Date('01/03/2016'), [1,0,0], [4,0,0]]
]);
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data, {
height: 600,
isStacked: true,
vAxis: {
format: 'HH:mm',
viewWindow: {
min: [0,0,0],
max: [24,0,0]
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="visualization"></div>

Related

Sending list information for google charts properly via flask to JS?

I'm mapping out ratings against episodes on a scatterplot on Google Charts. I have properly set the code up to send
data = [1, 8.7],[2, 8.8],[3, 8.3],[4, 8.4],[5, 9.3],[6, 8.9],[8, 9.3],[9, 8.4],[10, 8.3],[11, 8.4],[12, 8.9],[13, 8.7],[14, 9.2],[15, 9.1],[16, 8.6],[17, 8.9],[18, 9.3],[19, 9.3],[21, 8.7],[22, 8.5],[23, 8.3],[24, 8.7],[25, 9.3],[26, 9.6],[27, 8.8],[28, 8.5],[29, 7.8],[30, 8.5],[31, 9.5],[32, 9.7],[34, 8.3],[35, 8.1],[36, 8.7],[37, 8.7],[38, 8.5],[39, 8.9],[40, 9.3],[41, 8.9],[42, 9.6]
From Python to my graph.
Python:
def SendtoHTML():
dataPoint = data
return render_template('Scatter.html', series = series,finalEpNum = finalEpNum,minRatingFinal = minRatingFinal ,dataPoint = dataPoint)
if __name__ == '__main__':
app.run()
Script:
<script>
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var series = '{{series}}';
var finalEpNum = '{{finalEpNum}}'
var minRatingFinal = '{{minRatingFinal}}'
var data1 = google.visualization.arrayToDataTable([
['Episode', 'Rating'],
]);
var options = {
title: series,
hAxis: {title: 'Episode', minValue: 1, maxValue: finalEpNum},
vAxis: {title: 'Rating', minValue: minRatingFinal , maxValue: 10},
legend: true
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data1, options);
}
Which currently creates a google charts graph with all blue points.
However, I want to change colors of the datapoints after a given [x] value until another given [x] value. Kinda like this graph I made in matplotlib where the colors change from blue to red after season 1 ends. How would I achieve this in python or JS?
you can use a style column role
in your JS, add the role as the last column heading.
(the style role should follow the series column it represents)
var data1 = google.visualization.arrayToDataTable([
['Episode', 'Rating', {role: 'style', type: 'string'}], // <-- add style role
]);
then in your data, you can add the color each point should be...
data = [1, 8.7, 'blue'],[2, 8.8, 'blue'],[3, 8.3, 'blue'],[4, 8.4, 'red'],[5, 9.3, 'red'],[6, 8.9, 'orange'],[8, 9.3, 'orange'],[9, 8.4, 'orange'],
Here is my working code now after properly formatting the data block.
Python
def SendtoHTML():
finalEpNumParsable = int(finalEpNum)
datapointTest = [[1, 8.7, "0000ff"],[2, 6.7, "orange"],[3, 8.7, "0000ff"],[4,6.7,'red']]
render = render_template('Scatter.html', dataPoint = datapointTest)
return render
JS
function drawChart() {
var dataPoint = {{ dataPoint | tojson }};
var series = '{{series}}';
var finalEpUnparsed = {{finalEpNum}}
var finalEpNum = parseInt(finalEpUnparsed, 10);
var minRatingFinal = '{{minRatingFinal}}'
var data1 = google.visualization.arrayToDataTable([
['Episode', 'Rating', { role: 'style', type: 'string' }], // <-- add style role
dataPoint[0]
]);
for (i = 1; i < finalEpNum-5; i++){
data1.addRows([dataPoint[i]]);}

Google chart api Invalid row index . Should be in the range [0-4]

I am trying to develop report for my organization for that I am using google charts I am using bar chart for my report.
Is is the java script code I am using to display chart if I hard code values in google.visualization.DataTable(); the bar chart renders properly. If I try to fetch values from java script object it shows error.enter image description here
The java script code i am using is
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
var obj = JSON.parse('<?php echo json_encode($enroled_course) ?>');
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawMaterial);
function drawMaterial() {
// alert(obj.toSource());
var data = new google.visualization.DataTable();
data.addColumn('string', 'Course Name');
data.addColumn('number', 'Completion Percentage');
data.addRows(20);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
var course_percent=val.id;
var course_name=val.fullname;
data.setCell(course_name,course_percent);
//console.log(val);
}
}
/*var data = new google.visualization.DataTable();
// Declare columns
data.addColumn('string', 'Employee Name');
data.addColumn('datetime', 'Hire Date');
// Add data.
data.addRows([
['Mike', {v:new Date(2008,1,28), f:'February 28, 2008'}], // Example of specifying actual and formatted values.
['Bob', new Date(2007,5,1)], // More typically this would be done using a
['Alice', new Date(2006,7,16)], // formatter.
['Frank', new Date(2007,11,28)],
['Floyd', new Date(2005,3,13)],
['Fritz', new Date(2011,6,1)]
]);*/
var materialOptions = {
chart: {
title: 'Enrolled courses Details'
},
hAxis: {
title: 'Completion Percentage',
minValue: 0
},
vAxis: {
title: 'Courses'
},
bars: 'vertical'
};
var materialChart = new google.charts.Bar(document.getElementById('chart_div'));
materialChart.draw(data, materialOptions);
}
</script>
<div id="chart_div"></div>
<div class="container">
<div class="row rounded">
<div class="col-sm border">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
</div>
</div>
I will be very grateful if someone could say why I am getting invalid row index error while I am trying to insert a string in data.setCell(); method. I saw similar error but couldn't find the reason.
data table method setCell takes the following arguments...
setCell(rowIndex, columnIndex, value);
you're trying to pass row values, which is causing the error...
data.setCell(course_name,course_percent);
instead, don't add the rows initially, (remove --> data.addRows(20);)
add them once you have the values...
see following snippet...
var data = new google.visualization.DataTable();
data.addColumn('string', 'Course Name');
data.addColumn('number', 'Completion Percentage');
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
var course_percent=val.id;
var course_name=val.fullname;
data.addRow([course_name,course_percent]);
}
}

Morris chart not showing the last xkey value with MVC

My Morris Chart is not showing the last xkey value:
Any ideia why?
My data is:
[{"Date":"2016-07-17","Average":0.0},{"Date":"2016-07-16","Average":0.0},{"Date":"2016-07-15","Average":4.125},{"Date":"2016-07-14","Average":0.0},{"Date":"2016-07-13","Average":0.0},{"Date":"2016-07-12","Average":0.0},{"Date":"2016-07-11","Average":0.0}]
The View:
<script>
var surveyLastDaysChartData = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.SurveyLastDaysChartData));
</script>
<div class="col-lg-6">
<div class="card-box">
<h4 class="header-title m-t-0">Média dos últimos 7 dias</h4>
<div id="dsb-survey-last-days-chart" style="height: 217px;"></div>
</div>
</div><!-- end col -->
The script to build it:
var _surveyLastDaysChartId = "dsb-survey-last-days-chart";
Morris.Line({
// ID of the element in which to draw the chart.
element: _surveyLastDaysChartId,
// Chart data records -- each entry in this array corresponds to a point on the chart.
data: surveyLastDaysChartData,
// The name of the data record attribute that contains x-values.
xkey: 'Date',
// A list of names of data record attributes that contain y-values.
ykeys: ['Average'],
// Labels for the ykeys -- will be displayed when you hover over the chart.
labels: ['Média'],
resize: true,
hideHover: 'auto',
ymax: 5
});
This happened to me too.
I'm not sure how Morris calculates its elements, but sometimes, it cuts off values on the x-axis when it exceeds the width.
The way I was able to fix it (it is a hack, though) was to use their gridTextSize option and change it to a smaller font-size.
Example:
Morris.Line({
...
gridTextSize: 10,
...
});
Another option, if your app allows you to shorten your date, it to use their xLabelFormat option to parse your dates into a smaller format.
Example:
var display_date = function(d) {
var month = d.getMonth() + 1,
day = d.getDate();
var formattedDay = month + '-' + day
return formattedDay; // Return "M-DD" format for date
}
Morris.Line({
...
xLabelFormat: function(x) { return display_date(x); },
...
});
It's the default behaviour of Morris.js when the label is too long. You can use xLabelAngle, is and angle in degrees from horizontal to draw x-axis labels:
Morris.Line({
// ID of the element in which to draw the chart.
element: _surveyLastDaysChartId,
// Chart data records -- each entry in this array corresponds to a point on the chart.
data: surveyLastDaysChartData,
// The name of the data record attribute that contains x-values.
xkey: 'Date',
// A list of names of data record attributes that contain y-values.
ykeys: ['Average'],
// Labels for the ykeys -- will be displayed when you hover over the chart.
labels: ['Média'],
resize: true,
hideHover: 'auto',
xLabelAngle: 60, //<-- add this
ymax: 5
});
Demo: https://jsfiddle.net/iRbouh/hpq42x7b/

How to delete date space in Google Charts and correct percentage display

I have a lot of values since 30 Nov 2015 to 29 Feb 2019. Since 29 Feb to 11 Apr is nothing, and then new values after 11 Apr.
If I use "date" type of axe, I will have a big space beetwen 29 Feb and 11 Apr: http://white-fund.com/#roiPage (left chart)
If I use string type of axe, I will have no grouping (no few days in 1 element) and no display by month.
I need date format, grouping and no space, like I get it in Excel: http://white-fund.com/pictures/total_roi.png
Code:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'x');
data.addColumn('number', 'ROI per day');
data.addColumn('number', 'Total ROI');
<?php
$db = new db();
$ROIRows = $db->select("roi");
if($ROIRows) foreach ($ROIRows as $ROIRow) {
echo "data.addRow([new Date(\"$ROIRow[date_time]\"), ". ($ROIRow['roi']/100) .", ". ($ROIRow['total_roi']/100) ."]);";
}
?>
var formatter = new google.visualization.NumberFormat({
pattern: '#,###%',
fractionDigits: 2
});
formatter.format(data, 1);
formatter.format(data, 2);
// Create and draw the visualization.
new google.visualization.ComboChart(document.getElementById('chart_div')).
draw(data, {curveType: "function", width: 540, height: 290,
vAxes:{
0: {title:'ROI per day', format: 'percent'},
1: {title:'Total ROI', format: 'percent'}
},
series:{
0:{targetAxisIndex:0, type: 'bars', logScale:false},
1:{targetAxisIndex:1, type: 'line', pointSize:7, logScale:false},
},
seriesType: 'bars'
}
);
}
google.charts.setOnLoadCallback(drawChart);
Another one problem: how to display percents in float, not int? I trying to use formatter, but it shows 272.52% as 273%.
Thank you!
To fill-in gaps, add interpolateNulls: true to your configuration options...
As for the number format, try this pattern --> '#,##0.00%'
and lose fractionDigits: 2

Show different suffix in Google Piechart

I have a piechart showing the result the total bandwidth of uplink/downlink.
Right now, they suffix is GB.
I struggling trying to display their suffix different.
Example,
Downlink in GB
Uplink in KB.
I have
<script>
google.setOnLoadCallback(drawChart);
function drawChart() {
console.log(color['downlink']);
var data = google.visualization.arrayToDataTable([
['Task', 'Bandwith'],
['Downlink', ({{$t_down_bytes}})],
['Uplink', ({{$t_up_bytes}})]
]);
var options = {
legend: 'buttom',
pieSliceText: 'value', // text | none
title: 'Total Bandwith Usage',
colors: [color['downlink'], color['uplink']],
width:'100%',
height: 400,
slices: {
1: {offset: 0.1}
},
};
var formatter = new google.visualization.NumberFormat({
fractionDigits:2,
suffix: ' GB'
});
formatter.format(data, 1);
var chart = new google.visualization.PieChart(document.getElementById('private'));
chart.draw(data, options);
}
</script>
I can someone can shed some light on this.
Any hints / suggestions on this will be much appreciated !
One way is just doing it yourself: (Correct way to convert size in bytes to KB, MB, GB in Javascript might help)
var data = google.visualization.arrayToDataTable([
['Task', 'Bandwith'],
['Downlink', {v:6.4672328, f:"6.46 GB"}],
['Uplink', {v:9.40213213, f:"9.40 KB"}]
]);
Note that v is the "real" value google uses to draw and f is the formatted value it will show
If you want to keep your google formatter, another way is to add this line after your formatter.format(data, 1);
data.setFormattedValue(1,1,data.getFormattedValue(1,1).replace("GB","KB"))
Which sets the formattedValue of row 1, column 1
Update taking into account you want to use a mix of both:
var data = google.visualization.arrayToDataTable([
['Task', 'Bandwith'],
['Downlink', $t_down_bytes],
['Uplink', $t_up_bytes],
]);
var formatter = new google.visualization.NumberFormat({
fractionDigits:2
});
formatter.format(data, 1);
data.setFormattedValue(0,1,data.getFormattedValue(0,1) + ' {{$t_down_bytes_suffix}}')
data.setFormattedValue(1,1,data.getFormattedValue(1,1) + ' {{$t_up_bytes_suffix}}')
For more info on setFormattedValue and getFormattedValue check
Google Datatable Documentation

Categories

Resources