Google visualization line chart not showing annotations (no error in javascript) - javascript

I am using the following code and while the chart loads fine, the annotations don't appear and furthermore there is no error returned.
Here is the same example in a jsfiddle. Beating my brains out over here. Thank you in advance if you can see what I cannot.
What gives?
// Load the Visualization API and the corechart package.
google.load("visualization", "1", {packages:["corechart"]});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'GIP'); // Implicit domain label col.
data.addColumn('number', 'Production Curve Percentage'); // Implicit series 1 data col.
data.addColumn({type:'string', role:'annotation'}); // annotation role col.
data.addRows([
[2.7334,0.94, 'note 1-1', ],
[1.7899,0.653, 'note 2-2', ],
[1.444,0.94, 'note 3-3', ],
[1.7704,0.789, 'note 4', ],
[1.7773,1.083, 'note 5', ],
[2.7703,1.308, 'note 6', ],
[1.7173,1.026, 'note 7', ],
]);
var options = {
title: 'GIP2 vs. performance',
annotations: {
textStyle: {
fontName: 'Times-Roman',
fontSize: 18,
bold: true,
italic: true,
color: '#871b47', // The color of the text.
auraColor: '#d799ae', // The color of the text outline.
opacity: 0.8 // The transparency of the text.
}
},
pointShape: 'circle',
pointSize: '4',
vAxis: {
title: 'Performance',
},
hAxis: {
title: "GIP",
//logScale: 'true',
//format: "####",
},
seriesType: "line",
trendlines: {
0: {
type: 'linear',
visibleInLegend: true,
visibleInLegend: true,
showR2: true,
}
}
}
var chart = new google.visualization.ScatterChart(document.getElementById('chart_GIPvsPCP'));
chart.draw(data, options);
};

Apparently Scattercharts don't support annotations yet. The easy workaround is to change:
var chart = new google.visualization.ScatterChart(document.getElementById('chart_GIPvsPCP'));
to
var chart = new google.visualization.LineChart(document.getElementById('chart_GIPvsPCP'));
and then specify:
lineWidth: 0,
to get the same effect.
Thanks Samuel Cook. Official response from Google here: https://code.google.com/p/google-visualization-api-issues/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Stars%20Modified%20Type%20Status%20Priority%20Milestone%20Owner%20Summary&groupby=&sort=&id=1817

Related

Merging External data into a Chart in NDVI IMAGE SERIES Google earth engine javascript api

Here is my code. Please help merge the two charts into one chart.
I am trying to merge the first dataset from the data table with the one in image collection on the same axis.
The idea is to merge demand and the supply.
//feature collection for Aoi
var table =ee.Geometry.Polygon(
[[[37.55303819518035, 0.3541521362992195],
[37.55303819518035, 0.33389645906159726],
[37.596554354237966, 0.33389645906159726],
[37.596554354237966, 0.3541521362992195]]], null, false);
//external dataset
var myTable = {
cols: [
{id: 'name', label: 'month', type: 'string'},
{id: 'name', label: 'demand', type: 'number'},
{id: 'name', label: 'supply', type: 'number'}],
rows: [
{c: [{v: 'Jan'}, {v: 38253956}]},
{c: [{v: 'Feb'}, {v: 10978102}]},
{c: [{v: 'Mar'}, {v: 12030632}]},
{c: [{v: 'Apr'}, {v: 908340}]},
{c: [{v: 'May'},{v: 303074}]}
],
};
//defining the header
var header = ui.Label(' Demand Curve', {fontSize: '30px', color: 'black',fontWeight: 'bold'});
print(header)
var chart = new ui.Chart(myTable, 'LineChart');
chart.setSeriesNames([' Demand'])
chart.setOptions({
title: 'Demand Curve',
hAxis: {title: 'Date', titleTextStyle: {italic: false, bold: true},gridlines: {count: 27}},
vAxis: {
title: ' Demand',
titleTextStyle: {italic: false, bold: true}
},
lineWidth: 1,
colors: [ 'FF0000'],
curveType: 'line',
maxPixels:90e9
});
print(chart);
//---End Of the external data--------
//Getting image collection data fir the ndvi
Map=ui.Map();
var s2a = ee.ImageCollection('COPERNICUS/S2_SR')
.filter(ee.Filter.date('2019-01-01', '2019-03-31'))
.select('B1','B2','B3','B4','B5','B6','B7','B8','B8A','B9','B11','B12')
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10))
.sort('system:time_start')
.map(function(s2a){return s2a.clip(table)})
// .set('system:time_start',date_start)
// .set('system:time_end',date_end)
// .sort('DATE_ACQUIRED');
Map.setCenter (37.577717495842506,0.3597340638009545,5);
var subndvi = s2a.map(
function(image) {
var ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
var ndvi2 =ndvi.gt(0.18).and(ndvi.lte(0.22)).clip(table)
.copyProperties(image,['system:time_start','system:time_end','system:index'])
var ndvi3 = ndvi.gt(0.22).and(ndvi.lte(0.27))
.copyProperties(image,['system:time_start','system:time_end'])
return ndvi2
})
var ndviChart = ui.Chart.image.series(subndvi, table, ee.Reducer.mean(), 1000);
ndviChart.setOptions({
title: 'NDVI(Supply Curve)',
vAxis: {title: 'NDVI', maxValue: 1},
hAxis: {title: 'Date', format: 'MM-yy', gridlines: {count: 7}},
maxPixels:90e9,
});
print(ndviChart)
//-----End Of Ndvi Data--------
The below image shows the two charts from the code above.
enter image description here
The following code will probably do something what you need:
var monthlyDemand = ee.List([
38253956, // jan
10978102, // feb
12030632, // mar
908340, // apr
303074, // may
0, // jun
0, // jul
0, // aug
0, // sep
0, // oct
0, // nov
0 // dec
])
var s2a = ee.ImageCollection('COPERNICUS/S2_SR')
.filter(ee.Filter.date('2019-01-01', '2019-03-31'))
.select('B1','B2','B3','B4','B5','B6','B7','B8','B8A','B9','B11','B12')
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10))
var subndvi = s2a.map(function(image) {
var ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
var ndvi2 = ndvi.gt(0.18).and(ndvi.lte(0.22))
var demand = monthlyDemand.get(ee.Number(image.date().getRelative('month', 'year')).int())
return ndvi2.addBands(ee.Image.constant(demand).float().rename('demand'))
.copyProperties(image, ['system:time_start'])
})
var ndviChart = ui.Chart.image.series(subndvi, aoi, ee.Reducer.mean(), 1000).setOptions({
title: 'NDVI(Supply Curve)',
vAxis: {
title: 'NDVI',
maxValue: 1
},
hAxis: {
title: 'Date',
format: 'MM-yy',
gridlines: { count: 7 }
},
series: {
0: { targetAxisIndex: 0 },
1: { targetAxisIndex: 1 }
},
maxPixels:90e9,
});
print(ndviChart)
https://code.earthengine.google.com/1efd62e93e075cceec00e5f148414681
You have two variables "myTable" and "subndvi". The data type for the former is a table whereas for the second you have used ui.Chart.Image.series(). Table chart and image collection charts are different. Either you have to download your image collection point data and merge them manually in MS excel and re-upload to GEE, the new data will have three variables columns supply and demand at their respective dates.
This is how data looks from the two charts
enter image description here
This is how the data should look like
enter image description here
and when you reupload to GEE, use feature by feature chart and it should get you these results. Make sure to normalize your y-axis data.
enter image description here
var chart_1 = ui.Chart.feature.byFeature({
features: ndvi_demand,
}).setOptions({
series:{
0: {color:'red', targetAxisIndex: 0 },
1: {color:'green', targetAxisIndex: 1 },
}
})
print(chart_1)
Code Link:
https://code.earthengine.google.com/25261edeb9ee44ac1c3ba545e4498d71
And I used a feature collection chart rather than Image Collection one. Lots of approaches Just waned to give you insight on what's happening in background.
best regards
Muddasir Shah

Highcharts mobile (and window) resizing. Axis overlapping

The following fiddle shows what is happening to my users in mobile when rotating between portrait and landscape.
On load, the chart shows up as desired.
Hit 'Step 1', the chart shrinks and is shown as desired.
Hit 'Step 2', the chart returns to original size, but the vertical axis labels overlap.
http://jsfiddle.net/burchw78/rwb7ms93/
I have tried chart.redraw(), but with no success. Any ideas?
$(function() {
var chart = Highcharts.chart('container', {
chart: {
type: 'bar',
renderTo: 'industrybasicbar'
},
title: {
text: 'All Private Industries Expected to Add Jobs by 2024'
},
xAxis: {
categories: ['Health care and social assistance', 'Professional and business services', 'Trade, transportation, and utilities', 'Leisure and hospitality', 'Manufacturing', 'Construction', 'Local government', 'Financial activities', 'Other services', 'Natural resources and mining', 'Private educational services', 'State government', 'Information', 'Federal government'
],
title: {
text: null
}
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Projected Growth',
data: [46300, 45700, 36200, 35800, 21100, 17600, 9600, 9100, 8800, 6100, 4700, 2800, 2000, -1000
],
negativeColor: 'black'
}]
});
$('#resize').click(function () {
chart.setSize(300, 300);
});
$('#resize2').click(function () {
chart.setSize(500, 300);
});
});
It seems to be a bug. I reported it here: https://github.com/highcharts/highcharts/issues/8510
Workaround:
Update textOverflow manually:
$('#resize').click(function() {
chart.setSize(300, 300);
chart.xAxis[0].update({
labels: {
style: {
textOverflow: 'ellipsis'
}
}
});
});
Live demo: http://jsfiddle.net/BlackLabel/axhcwrmd/

How do I show x axis labels in a Google LinChart

I'm trying out Google charts for rendering a line chart for my app. Things mostly work, I get the following:
The one remaining issue I have is that I am only getting a single x-axis label. (The 12:00).
I'd like to show more x-axis labels, so I tried adding a gridlines property:
// Line chart visualization
var myLine = new google.visualization.ChartWrapper({
'chartType': 'LineChart',
'containerId': 'line_div'
});
myLine.setOptions({
'title': 'My Chart',
lineWidth: 1,
colors: ['#006600', '#FF0000'],
vAxes: [
{title: 'AAA', titleTextStyle: {color: '#000000'}}, // Left axis
{title: 'BBB', titleTextStyle: {color: '#000000'}} // Right axis
],
hAxis: {
format: 'hh:mm',
gridlines: {count: 20}
},
series: [
{targetAxisIndex: 1},
{targetAxisIndex: 0}
]
});
But no luck, it still only displays one label and no x-axis gridlines.
How do I get more x-axis labels?
The problem turned out to be how I was populating my DataTable. I was using:
dataTable.addColumn({type: 'date', label: 'Date'})
because in my thinking a new Date() is a date. Google charts has a different opinion, so what I needed to do was:
dataTable.addColumn({type: 'datetime', label: 'Date'})
and that sorted it.

Google line chart show all custom tooltips

I have to create a line chart where a few of the points have tooltips or other balloons/captions/texboxes with information about the point. They must always be displayed, not only on mouse over. Basically a google annotation chart, but with the data on the chart.
I tried the code below, which doesn't even show the tooltip as it should. Any thoughts, or should I choose a different technology? Thanks.
google.load('visualization', '1.1', { packages: ['line'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Day');
data.addColumn('number', 'Score');
data.addColumn({type: 'string', role: 'tooltip' });
data.addRows([
[1, 37, 'This score occurred in Texas in 1959.'],
[2, 30, ''],
[3, 25, ''],
]);
var options = {
chart: {
title: 'Important Chart',
subtitle: 'in millions of dollars (USD)'
},
width: 900,
height: 500,
legend: 'none',
axes: {
x: {
0: { side: 'top' }
}
}
};
var chart = new google.charts.Line(document.getElementById('line_top_x'));
chart.draw(data, options);
}
You would want to use role:'annotation' instead of role: 'tooltip'. Annotation allows you to display the text without any user interaction. See the documentation on annotationRole for more info.
Working Code: http://jsfiddle.net/wkyg2brg/
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Day');
data.addColumn('number', 'Score');
data.addColumn({type:'string', role:'annotation'});
data.addRows([
[1, 37, 'This score occurred in Texas in 1959.'],
[2, 30, ''],
[3, 25, ''],
]);
var options = {
chart: {
title: 'Important Chart',
subtitle: 'in millions of dollars (USD)'
},
width: 900,
height: 500,
legend: 'none',
axes: {
x: {
0: { side: 'top' }
}
}
};
var chart = new
google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options);
}

Add a note/message to Google Charts at specific places

I am using Google Charts to display some data related to the performance of a web page (bounce rate, volume, etc). When I make changes to the page (for example changing the color of a button), I keep track of that using small notes (for example: 'week 15 2014: button is now green').
I'd like to display these notes (with a hover-over function to display the text) IN the chart. So vertically they should be at the right location (right week). Horizontally it doesn't matter where they're placed, on top or bottom would be most logical. What would be the best approach to succeed in doing so?
JSFiddle of my current chart: http://jsfiddle.net/9qukjbhg/
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Interval', 'Bounce Rate', 'Call to Action Succeed', 'Total Volume'],
['week 36', 0.3283, 0.4328, 67],
['week 37', 0.2857, 0.4167, 84],
['week 38', 0.1562, 0.5417, 96],
['week 39', 0.275, 0.4125, 80],
['week 40', 0.2615, 0.4154, 65],
['week 41', 0.2213, 0.3588, 131],
['week 42', 0.2232, 0.5, 112],
['week 43', 0.3476, 0.3898, 118],
['week 44', 0.3025, 0.4118, 119],
['week 45', 0.294, 0.3897, 136],
['week 46', 0.2043, 0.4286, 49]
]);
var formatter = new google.visualization.NumberFormat({
pattern: '#,###%'
});
formatter.format(data, 1);
formatter.format(data, 2);
var options = {
vAxes: {
0: {
format: '#,###%'
},
gridlines: {
color: 'transparent'
}
},
1: {
gridlines: {
color: 'transparent'
}
},
series: {
0: {
targetAxisIndex: 0,
type: 'bars'
},
1: {
targetAxisIndex: 0,
type: 'bars'
},
2: {
targetAxisIndex: 1
}
},
title: 'Page performance per week'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
What I try to do (something like this, see the note on the right top of the image):
Who can point me in the right direction? Many thanks in advance!

Categories