Amcharts SerialChart multiple line graphs different category value member paths (Silverlight) - silverlight

EDIT I rewrote my question to make it more understandable after the conversation below with Tony (thanks!).
GOAL Render multiple line graphs (let's say 2) in the same chart. The charts have different x/y value pairs. For one x-value, I do not know both y-values.
I am using Silverlight. The classes available for this are SerialChart and LineGraph. The data source for both graphs is the same and is set at the SerialChart level. The name of the property for the x-axis is also defined there for both graphs (CategoryValueMemberPath).
As suggested by the amCharts documentation, we need to create objects that have a property for the category axis (x-axis) and then one property per graph. Let's call them "Graph1" and "Graph2". So the data source looks something like this:
List<MyClass> data = new List<MyClass>()
{
new MyClass() { Category = 0.1, Graph1 = 0.14, Graph2 = ??? }
,new MyClass() { Category = 0.15, Graph1 = ???, Graph2 = 0.05 }
,new MyClass() { Category = 0.2, Graph1 = 0.35, Graph2 = ??? }
,new MyClass() { Category = 0.18, Graph1 = ???, Graph2 = 0.12 }
... and so on ...
}
PROBLEM What am I supposed to do about the "???" values? I do not have the actual value for that graph for that category value.
If I do not set a value, the default value of 0.0 is assumed and it draws a spike to the x-axis. If I set the previously known Graph1/Graph2 value, then it creates a horizontal connection where there is not supposed to be one. I am basically altering the graph which leads to a wrong result.
So how do I solve this? I am getting the feeling that amCharts do not support this scenario.

You need to add two 'value' axes, one in the X direction and one in the Y direction (imagine, like a bubble chart).
// AXES
// X
var xAxis = new AmCharts.ValueAxis();
xAxis.position = "bottom";
xAxis.gridAlpha = 0.1;
xAxis.autoGridCount = true;
chart.addValueAxis(xAxis);
// Y
var yAxis = new AmCharts.ValueAxis();
yAxis.position = "left";
yAxis.gridAlpha = 0.1;
yAxis.autoGridCount = true;
chart.addValueAxis(yAxis);
Merge all your data points into one array with a common X axis field name ('x' in my example) and for points on line 1, add a property of 'line1' with its value, and for points on line 2, add a property of 'line2'.
For example, your data would look like this:
var chartData = [
{x:0.1,line1:0.25},
{x:0.246,line1:0.342},
{x:0.12,line2:0.16},
{x:0.3,line2:0.485}
];
Then add a 'graph' for each line to your chart specifying where to get the value from in the object array.
// GRAPHS
var graph = new AmCharts.AmGraph();
graph.xField = "x";
graph.yField = "line1";
graph.lineAlpha = 1;
graph.lineColor = '#FF9E01';
chart.addGraph(graph);
var graph2 = new AmCharts.AmGraph();
graph2.xField = "x";
graph2.yField = "line2";
graph.lineAlpha = 1;
graph2.lineColor = '#9EFF01';
chart.addGraph(graph2);
I've put all this into a Fiddle for you - http://jsfiddle.net/64EWx/

Related

Iterate over ee.FeatureCollection to compute regional statistics of an ee.ImageCollection

Dear Earth Engine community,
Can someone help me solving the following problem:
I want to compute the aggregate nightlight intensities (sum) within all first level administrative regions of the world. For that purpose I use a shapefile which contains the regional boundaries (GADM) and raster data on nightlight (VIIRS).
The issue with the following code is that 1) I am getting an error that say "Unknown element type provided: object. Expected: ee.Image, ee.ImageCollection, ee.FeatureCollection or ee.Element." for the nighttime.reduceRegion operation and 2) that only the last feature of the selection is returned on print(final).
Unfortunately I do not manage to solve these problems. It would be great if someone could help me improving the code. I am sure there are many issues since Javascript and the Earth Engine API are completely new to me..
Thanks a lot in advance!
// Import nighttime raster data.
var nighttimeCollection = ee.ImageCollection('NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG');
// Import shapefile containing region boundaries.
var region_boundaries = ee.FeatureCollection("users/hendrikscheewel/gadm_level_1");
// Select a specific year ::: Later this should be done within a loop.
var year = "2014";
// Aggregate monthly nighttime data to year x.
var nighttime = nighttimeCollection
.filter(ee.Filter.date(year+'-01-01', year+'-12-31'))
.select('avg_rad')
.reduce(ee.Reducer.mean());
// This function does the following:
// * Aggregrate nightlight data within a shape/feature by taking its sum,
// * Assign the result to the feature,
// * Create copy of feature with simplified geometry (centroid) and fewer columns,
// * Return the copy.
var compute_nightlight = function(feature) {
// Compute mean of average radiance for feature shape
var result = nighttime.reduceRegion({
geometry: feature.geometry(),
reducer: ee.Reducer.sum(),
scale: 30,
maxPixels: 1e9,
});
// Set "nightlight" as a new property.
feature = ee.Feature(feature.set('nightlight',result.get('avg_rad_mean')));
// Get the centroid of the feature's geometry.
var featureSimplified = feature.centroid();
// Keep this list of properties.
var keepProperties = ['GID_0','GID_1','NAME_0','NAME_1','nightlight'];
featureSimplified = featureSimplified.copyProperties(feature, keepProperties);
// Return a new Feature, copying properties from the old Feature.
return featureSimplified;
};
//print(compute_nightlight(region_boundaries.first()));
var final = region_boundaries.filter(ee.Filter.eq('NAME_0','Belgium')).iterate(compute_nightlight);
print(final)
Export.table.toDrive({
collection: final,
description: 'nl_'+year,
fileFormat: 'CSV'
});
Ok, I found my main mistake: Instead of using the .iterate() method I should have used the .map() method.
After some cleaning the code looks like this:
// Select a specific year
var year = "2014";
// Aggregate monthly nighttime data to year x.
var nighttime = nighttimeCollection
.filter(ee.Filter.date(year+'-01-01', year+'-12-31'))
.select('avg_rad')
.reduce(ee.Reducer.mean());
// This function does the following:
// * Aggregrate nightlight data within a shape/feature by taking its sum,
// * Assign the result to the feature,
// * Create copy of feature with simplified geometry (centroid) and fewer columns,
// * Return the copy.
var compute_nightlight = function(feature) {
// Compute mean of average radiance for feature shape
var result = nighttime.reduceRegion({
geometry: feature.geometry(),
reducer: ee.Reducer.sum(),
scale: 30,
maxPixels: 1e9,
});
// Set "nightlight" as a new property.
feature = ee.Feature(feature.set('nightlight',result.get('avg_rad_mean')));
// Return a new Feature, copying properties from the old Feature.
return feature.centroid();
};
var final = ee.FeatureCollection((region_boundaries).map(compute_nightlight));
Export.table.toDrive({
collection: final,
description: 'nl_'+year,
fileFormat: 'CSV'
});

Swift - Update and store position of a multiple programmatically created buttons

I have a button which creates other buttons based on the class Clip seen below. Those newly created buttons are added to an array and stored in a plist.
class Clip: Encodable, Decodable {
var name: String = ""
var xCoordinate: Int = 100
var yCoordinate: Int = 300
// more parameter will be added later on e.g color, scale etc..
}
Each button can be moved around the view and the new x & y coordinates are stored in a plist.
#objc func handlePan(sender: UIPanGestureRecognizer){
let uIViewSelected = sender.view!
switch sender.state {
case .began, .changed :
moveViewWithPan(view: uIViewSelected, sender: sender)
break
case .ended:
//Finds the position when the button is no longer being dragged
let x = Int(uIViewSelected.center.x)
let y = Int(uIViewSelected.center.y)
//clipArray[0] need to be the corresponding clicked button e.g clipArray[2]
clipArray[0].xCoordinate = x
clipArray[0].yCoordinate = y
saveData()
break
default:
break
}
}
The above works only if I create one button. When more buttons are added, the above lines only change the first clip from the array. I need a way to update the value to the correct button clicked.
How can identify the array position of the click button as I am creating all them programmatically? At the moment I am placing at value 0 of the clipArray.
clipArray[0].xCoordinate = x
clipArray[0].yCoordinate = y
I am not even sure if using a plist is the best way to store the buttons in the first place.
Any help or documentation would be much appreciated.
Thanks
Following from dfd response, I added tags to each button which are created and it solved the issue for now.
let x = Int(uIViewSelected.center.x)
let y = Int(uIViewSelected.center.y)
//clipArray.append(clip)
var tagNo = uIViewSelected.tag
clipArray[tagNo].xCoordinate = x
clipArray[tagNo].yCoordinate = y

Google Earth Engine - error 'Cannot export array bands.' How to export map layer of cross-covariance as Geotiff?

I have computed and displayed as a map layer the cross-covariance of Landsat-derived NDVI and CHIRPS precipitation data.
I now want to export this as an image, clipped to my region of interest, but am getting the following error:
Error 'Cannot export array bands'
I have not managed to find a solution. Is there a way to export this map layer as geotiff? I think perhaps I need to flatten the array but am unsure how to do this.
Here is the code below:
l8toa = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA")
//Define a region of interest - Baringo county, kenya
var Baringo2 = /* color: #98ff00 */ee.Geometry.Polygon(
[[[35.69382363692023, 1.4034169899773616],
[35.69382363692023, 1.2606333558875118],
[35.61691934004523, 1.0079975313237526],
[35.58945351973273, 0.6509798625215468],
[35.71030312910773, 0.35436075019447294],
[35.72128945723273, 0.18956774160826206],
[35.61691934004523, 0.18407460674896256],
[35.58945351973273, 0.13463632293582842],
[35.71030312910773, 0.04125265421470341],
[35.68283730879523, -0.0466379620709295],
[35.74875527754523, -0.18945988757796725],
[35.96848184004523, 0.05223897866641199],
[36.09482461348273, 0.002800509340276178],
[36.27060586348273, 0.2719645271288622],
[36.23215371504523, 0.45872822561768967],
[36.32004434004523, 0.6509798625215468],
[36.47934609785773, 0.8651943843139164],
[36.32004434004523, 0.9915205478901427],
[36.18271523848273, 1.1672705367627716],
[36.08933144942023, 1.1892385469740003],
[35.79270059004523, 1.6944479915417494]]]);
//print (Baringo2);
//Add Baringo
Map.addLayer(ee.Image().paint(Baringo2, 0, 2), {}, 'Baringo_county');
Map.centerObject(Baringo2);
//B) Filtering, masking and preparing bands of interest
//preprocess the Landsat 8 imagery by filtering it to the location of interest, masking clouds,
//and adding the variables in the model:
// This field contains UNIX time in milliseconds.
var timeField = 'system:time_start';
// Use this function to mask clouds in all Landsat imagery.
var maskClouds = function(image) {
var quality = image.select('BQA');
var cloud01 = quality.eq(61440);
var cloud02 = quality.eq(53248);
var cloud03 = quality.eq(28672);
var mask = cloud01.or(cloud02).or(cloud03).not();
return image.updateMask(mask);
};
// Use this function to add variables for NDVI, time and a constant
// to Landsat 8 imagery.
var addVariablesl8 = function(image) {
// Compute time in fractional years since the epoch.
var date = ee.Date(image.get(timeField));
var years = date.difference(ee.Date('1970-01-01'), 'year');
// Return the image with the added bands.
return image
// Add an NDVI band.
.addBands(image.normalizedDifference(['B5', 'B4']).rename('NDVI'))
.float()
// Add a time band.
.addBands(ee.Image(years).rename('t').float())
// Add a constant band.
.addBands(ee.Image.constant(1));
};
// Remove clouds, add variables and filter to the area of interest - landsat 8.
var filteredLandsatl8 = l8toa
.filterDate('2013-02-07', '2018-08-25')
.filterBounds(Baringo2)
.map(maskClouds)
.map(addVariablesl8);
// Cross-covariance is measuring the correspondence between a variable and a covariate at a lag.
//Create a lagged ImageCollection
var lag = function(leftCollection, rightCollection, lagDays) {
var filter = ee.Filter.and(
ee.Filter.maxDifference({
difference: 1000 * 60 * 60 * 24 * lagDays,
leftField: timeField,
rightField: timeField
}),
ee.Filter.greaterThan({
leftField: timeField,
rightField: timeField
}));
return ee.Join.saveAll({
matchesKey: 'images',
measureKey: 'delta_t',
ordering: timeField,
ascending: false, // Sort reverse chronologically
}).apply({
primary: leftCollection,
secondary: rightCollection,
condition: filter
});
};
//This function joins a collection to itself, using a filter that gets all the images before but within a specified time difference (in days) of each image.
//That list of previous images within the lag time is stored in a property of the image called images, sorted reverse chronologically.
//Compute cross covariance
//i) The covariance reducer expects a set of one-dimensional arrays as input.
//So pixel values corresponding to time t need to be stacked with pixel values at time t ? l as multiple bands in the same image.
var merge = function(image) {
// Function to be passed to iterate.
var merger = function(current, previous) {
return ee.Image(previous).addBands(current);
};
return ee.ImageCollection.fromImages(
image.get('images')).iterate(merger, image);
};
//...use that function to merge the bands from the lagged collection:
//Use a function to convert the merged bands to arrays with bands pt and ph, then reduce with the covariance reducer:
var covariance = function(mergedCollection, band, lagBand) {
return mergedCollection.select([band, lagBand]).map(function(image) {
return image.toArray();
}).reduce(ee.Reducer.covariance(), 8);
};
//is NDVI related in some way to the precipitation before the NDVI was observed?
//To estimate the strength of this relationship (in every pixel),
//load precipitation, join, merge, and reduce as previously:
// Load Precipitation data (covariate)
var chirps = ee.ImageCollection('UCSB-CHG/CHIRPS/PENTAD');
// Join the t-l (l=1 pentad) precipitation images to the Landsat.
var lag1PrecipNDVI = lag(filteredLandsatl8, chirps, 5);
// rainfall 5 days previous - aimed at annual grasses that respond quickly
// Add the precipitation images as bands.
var merged1PrecipNDVI = ee.ImageCollection(lag1PrecipNDVI.map(merge));
// Compute, visualise and display cross-covariance.
var cov1PrecipNDVI = covariance(merged1PrecipNDVI, 'NDVI', 'precipitation');
// create vizualization parameters
var viz = {min:-0.5, max:0.5, palette:['0000FF', '008000', 'FF0000']};
Map.addLayer(cov1PrecipNDVI.arrayGet([0, 1]).clip(Baringo2), viz, 'NDVI - PRECIP cov (lag = 5), Baringo');
//red is high cross covariance and blue is low covariance between NDVI and precipitation 5 days previously
// Export the cov1PrecipNDVI image, specifying scale and region.
Export.image.toDrive({
folder: 'Baringo_Remote_Sensing',
image: cov1PrecipNDVI,
description: 'NDVI - PRECIP cov (lag = 5)',
scale: 30,
region: Baringo2,
maxPixels: 1e10
});
Can anyone help me please?
Thank you.

Data and Series label not showing on WinForm Chart control

I am having a problem getting the default WinForms Chart control to work. I have a single chart with a single area. In this area, I want to display three (3) series whose labels are on a single legend.
Each of the value arrays shown in the code below contains six (6) values.
When I run the application the chart is only showing the background with the title and the name of the FIRST series I defined, the others seem to be ignored. Also, no grid and no data points or lines are displayed. The chart is basically blank.
this.chart.SuspendLayout();
this.chart.ChartAreas.Clear();
this.chart.Series.Clear();
ChartType chartType = ChartType.Column;
// prepare the area
const string AREA_NAME = "ChartAreaBP";
ChartArea bpChartArea = new ChartArea(AREA_NAME);
bpChartArea.AxisX.LabelStyle.Format = "dd/MMM\nyyyy";
bpChartArea.AxisX.MajorGrid.LineColor = System.Drawing.Color.LightGray;
bpChartArea.AxisY.MajorGrid.LineColor = System.Drawing.Color.LightGray;
bpChartArea.BackColor = System.Drawing.Color.LimeGreen;
bpChartArea.BackGradientStyle = GradientStyle.DiagonalRight;
bpChartArea.Position.Auto = true;
bpChartArea.InnerPlotPosition.Auto = true;
this.chart.ChartAreas.Add(bpChartArea);
// prepare the values. X is Date/time all other 3 are BYTE/INT
var xvals = from x in items select x.TimeStamp;
var yvalsSys = from y in items select y.Systolic;
var yvalsDia = from y in items select y.Diastolic;
var yvalsRhy = from y in items select y.Rhythm;
// The first series, other 2 omitted from HERE for simplicity
const string SYS_SERIES = "Systolic";
Series sysBPSeries = new Series(SYS_SERIES, 4);
sysBPSeries.ChartType = chartType;
sysBPSeries.ChartArea = AREA_NAME;
sysBPSeries.XValueType = ChartValueType.Auto;
sysBPSeries.YValueType = ChartValueType.Date;
sysBPSeries.XAxisType = AxisType.Primary;
sysBPSeries.YAxisType = AxisType.Primary;
sysBPSeries.Enabled = true;
this.chart.Series.Add(sysBPSeries);
this.chart.Series[SYS_SERIES].Points.DataBindXY(xvals, yvalsSys);
// here the other two series are defined.
But when I run the application only the legend of the FIRST series is shown even though the other two are defined in the code (I omitted them from this listing) just the same way as the first series.
And as I stated above, no grid nor values are shown. However, the chart shown in design mode does show all three labels on the first and only legend and all three lines.

Swift - Create circle and add to array

I've been looking for a little while on how to create a circle in Swift, but it seems quite complicated. I want to create a circle at run time, with a specified x and y, and width and height. I then want to add this circle to an array where I can create more circles and add to it.
How do I do this?
Edit: This is what I've tried so far:
var center : CGPoint = touchLocation
var myContext : CGContextRef = UIGraphicsGetCurrentContext()
let color : [CGFloat] = [0, 0, 1, 0.5]
CGContextSetStrokeColor (myContext, color);
CGContextStrokeEllipseInRect (myContext, CGRectMake(touchLocation.x, touchLocation.y, 20, 20));
touchLocation is the location of the users finger. This crashes on execution on this line:
var myContext : CGContextRef = UIGraphicsGetCurrentContext()
The error says "Unexpectedly found nil while unwrapping an Optional value
Also, this doesn't allow me to add the circle to an array, because I don't know what variable type it is.
There are many ways to draw a circle, here is a snippet that I have been hacking with:
func circleWithCenter(c:CGPoint, radius r:CGFloat,
strokeColor sc: UIColor = UIColor.blackColor(),
fillColor fc: UIColor = UIColor.clearColor()) -> CAShapeLayer {
var circle = CAShapeLayer()
circle.frame = CGRect(center:c, size:CGSize(width:2*r, height:2*r))
circle.path = UIBezierPath(ovalInRect:circle.bounds).CGPath
circle.fillColor = fc.CGColor
circle.strokeColor = sc.CGColor
circle.fillColor = fc == UIColor.clearColor() ? nil : fc.CGColor
return circle
}
Note that I extended CGRect (using Swift specific features) to add a initializer that takes a center, but that is not material to your question.
Your code is not "creating" a circle as an object, it is attempting to draw one in the graphics context. What you need to do is to create a bezier path object, draw into that and save the path in your array. Something like:
var circleArray = [CGMutablePathRef]()
// ...
let path: CGMutablePathRef = CGPathCreateMutable()
CGPathAddArc(path, nil, touchLocation.x, touchLocation.y, radius, 0, M_PI * 2, true)
circleArray += [path]
You then need to stroke the path(s) in your draw routine.

Resources