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
Related
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]]);}
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/
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>
I am using the Google visualization tools to show a table, but all of my HTML is being shown as a string. Here is the code:
var data = new google.visualization.DataTable()
data.setTableProperty('allowHtml', true)
data.addColumn('string','Keyword')
data.addColumn('number','<img src="http://m8app.com/assets/google-icon-8556487cd6ff3508d7bf2c4f64a0e3ad.jpg">Rank')
data.addColumn('number','Rank Change')
data.addColumn('string','Page')
data.addColumn('string','Link')
var row = 1;
while(row < thing.length){
data.addRow([
thing[row][0],
parseInt(thing[row][1],10),
parseInt(thing[row][2],10),
thing[row][3],
"<a href='"+thing[row][4]+"' target='_blank'>Search</a>"]);
row++;
}
var table = new google.visualization.Table(document.getElementById('rankInner'));
table.draw(data, {
allowHtml:true,
showRowNumber: false,
page : 'enable',
pageSize:10,
sortColumn: 2,
sortAscending:false
});
I have set 'allowHtml' to true on both the DataTable and the Table, but the table still shows the full text of the HTML rather than rendering it as html. I'd be grateful for any recommendation to try, thank you.
I tried a sample like yours in the online visualization playground, and it seems good
The only line I see you got messed up is the below line, where the indentation is wrong [quotes, double quotes. Compare with the below working one]
"<a href='"+thing[row][4]+"' target='_blank'>Search</a>"]);
link : https://code.google.com/apis/ajax/playground/?type=visualization#table
Code I tried:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Name', 'Height', 'Dance'],
['Kuttappan', 174, true],
['Raayappan', 523, false],
["<a href='abc.com' target='_blank'>Search</a>", 86, true]
]);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {allowHtml:true});
}
when you run it [click on RunCode in the tool], you see the search link, and not the HTML code.
The below code for image,
data.addColumn('number','<img src="http://m8app.com/assets/google-icon-8556487cd6ff3508d7bf2c4f64a0e3ad.jpg">Rank')
is indeed showing as image only, and not HTML
So I have a Google Motion chart that displays data over time. A PHP is calling to a database to get data for the chart, that data is store into a JS file, and then the html file draws the chart (using a js script).
I want there to be a user input:
Start (millions):<input class="option" type="text" id="start" name="start" value="<?php echo $start?>"></input> |
End (millions): <input class="option" type="text" id="end" name="end" value="<?php echo $end?>"></input> |
where the user input will set the x values of the charts (which is in millions)
HTML and JS SCRIPT THAT DRAWS THE GRAPH:
function dataLoaded(myData) {
};
google.load('visualization', '1', {'packages':['motionchart']});
google.setOnLoadCallback(drawChart);
var control = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'options': {
// Filter by the date axis.
'filterColumnIndex': 0,
'ui': {
'chartType': 'MotionChart',
'chartOptions': {
'chartArea': {'width': '90%'},
},
}
},
});
function drawChart() {
// alert("dataLoaded called");
var chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Moving Avg Volume');
chartData.addRows(chartDataRows);
var upOptions = {};
upOptions['state'] = {"playDuration":15000,"orderedByY":false,"iconType":"VBAR","yAxisOption":"6","nonSelectedAlpha":0.4,"yZoomedDataMin":0,"showTrails":false,"yZoomedDataMax":2.2,"xAxisOption":"6","iconKeySettings":[],"duration":{"multiplier":1,"timeUnit":"D"},"xZoomedDataMin":0,"yLambda":1,"yZoomedIn":false,"uniColorForNonSelected":false,"xZoomedIn":false,"dimensions":{"iconDimensions":["dim0"]},"orderedByX":true,"sizeOption":"_UNISIZE","xZoomedDataMax":122,"xLambda":1,"colorOption":"4"};
upOptions['width'] = 900;
upOptions['height'] = 600;
var upchart = new google.visualization.MotionChart(document.getElementById('who_up_chart'));
upchart.draw(chartData, upOptions);
var downOptions = {};
downOptions['state'] = {"playDuration":15000,"orderedByY":false,"iconType":"VBAR","yAxisOption":"5","nonSelectedAlpha":0.4,"yZoomedDataMin":0,"showTrails":false,"yZoomedDataMax":24000,"xAxisOption":"5","iconKeySettings":[],"duration":{"multiplier":1,"timeUnit":"D"},"xZoomedDataMin":0,"yLambda":1,"yZoomedIn":false,"uniColorForNonSelected":false,"showXScalePicker":true,"xZoomedIn":false,"dimensions":{"iconDimensions":["dim0"]},"orderedByX":true,"showYMetricPicker":true,"sizeOption":"_UNISIZE","xZoomedDataMax":122,"xLambda":1,"colorOption":"4"};
downOptions['width'] = 900;
downOptions['height'] = 600;
var downchart = new google.visualization.MotionChart(document.getElementById('who_down_chart'));
downchart.draw(chartData, downOptions);
document.getElementById('loading').innerHTML='';
}
My X axis is from 0 to 100,000,000, and so if the user enters in 1,000,000 to 5,000,000 I want the chart to redraw and show only those points.
I think what you're looking for is a DataView. A DataView is like an interface for changing how you view the data in a DataTable without actually changing the data.
var data = new google.visualization.DataTable();
var options = {
//set your options
}
//Load Your Data Here.
var view = new google.visualization.DataView(data);
view.setRows(view.getFilteredRows([{column: 0, minValue: minTime, maxValue: maxTime}]);
var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
chart.draw(view, options)
I also noticed that you declare a ChartRangeFilter control at the beginning. To bind that to a chart the both need to be part of a google.visulization.Dashboard. I was unable to determine if a MotionChart is capable of binding with a control, but you could give it a try and find out.