dimple js straight line y-axis over bar chart - javascript

I am trying to draw Average, High and Low value straight line on a dimple js bar chart. I have no clue how they can be drawn on y-axis (cost) as straight line that will cut through the bars. Here is the fiddle that has high, low and average values saved into corresponding variable that needed to be drawnon the chart. Any solution? jsfiddle link: http://jsfiddle.net/Ra2xS/14/
var dim = {"width":590,"height":450}; //chart container width
var data = [{"date":"01-02-2010","cost":"11.415679194952766"},{"date":"01-03-2010","cost":"10.81875691467018"},{"date":"01-04-2010","cost":"12.710197879070897"}];
//y- axis (cost) values to plot as straight line over bar chart in different colours
var avg = "11.65";
var high= "12.71";
var low = "10.82";
function barplot(id,dim,data)
{
keys = Object.keys(data[0]);
var xcord = keys[0];
var ycord = keys[1];
var svg = dimple.newSvg(id, dim.width, dim.height);
var myChart = new dimple.chart(svg,data);
myChart.setBounds(60, 30, 505, 305);
var x = myChart.addCategoryAxis("x", xcord);
x.addOrderRule(xcord);
x.showGridlines = true;
var y = myChart.addMeasureAxis("y", ycord);
y.showGridlines = true;
y.tickFormat = ',.1f';
var s = myChart.addSeries(null, dimple.plot.bar);
var s1 = myChart.addSeries(null, dimple.plot.line);
s1.lineWeight = 3;
s1.lineMarkers = true;
myChart.draw(1500);
}
barplot("body",dim,data);

You can do it by adding a separate series with it's own data, unfortunately there's a bug with multiple line series in version 1.1.5 which means line markers go haywire (so I've removed them from the code below). The good news is I've just finished rewriting all the line chart code and this problem will be fixed in the next version (coming in a week or so), also the line will animate properly by rising from the x axis instead of fading in from black.
var dim = {"width":590,"height":450}; //chart container width
var data = [{"date":"01-02-2010","cost":"11.415679194952766"},{"date":"01-03-2010","cost":"10.81875691467018"},{"date":"01-04-2010","cost":"12.710197879070897"}];
function barplot(id,dim,data)
{
keys = Object.keys(data[0]);
var xcord = keys[0];
var ycord = keys[1];
var svg = dimple.newSvg(id, dim.width, dim.height);
var parser = d3.time.format("%d-%m-%Y")
var dateReader = function (d) { return parser.parse(d[xcord]); }
var start = d3.time.month.offset(d3.min(data, dateReader), -1);
var end = d3.time.month.offset(d3.max(data, dateReader), 1);
var myChart = new dimple.chart(svg,data);
myChart.setBounds(60, 30, 505, 305);
//var x = myChart.addCategoryAxis("x", xcord);
var x = myChart.addTimeAxis("x", xcord, "%d-%m-%Y","%b %Y");
x.overrideMin = start;
x.overrideMax = end;
x.addOrderRule(xcord);
x.showGridlines = true;
x.timePeriod = d3.time.months;
x.floatingBarWidth = 100;
var y = myChart.addMeasureAxis("y", ycord);
y.showGridlines = true;
y.tickFormat = ',.1f';
var s1 = myChart.addSeries(null, dimple.plot.bar);
var s2 = myChart.addSeries(null, dimple.plot.line);
s2.lineWeight = 3;
var s3 = myChart.addSeries("Price Break", dimple.plot.line);
s3.data = [
{ "Price Break" : "high", "cost" : 12.71, "date" : parser(start) },
{ "Price Break" : "high", "cost" : 12.71, "date" : parser(end) },
{ "Price Break" : "avg", "cost" : 11.65, "date" : parser(start) },
{ "Price Break" : "avg", "cost" : 11.65, "date" : parser(end) },
{ "Price Break" : "low", "cost" : 10.82, "date" : parser(start) },
{ "Price Break" : "low", "cost" : 10.82, "date" : parser(end) }
];
myChart.draw(1500);
}
barplot("body",dim,data);
http://jsfiddle.net/Ra2xS/28/

Related

GEE Animation, print thumbnail black

The following code is conceived to create a thumbnail image of landsat 7 images:
// Feature Collection
var aoi = geometry
print(aoi);
Map.addLayer(aoi);
var centroid = aoi.centroid(1)
print(centroid);
var coors = centroid.coordinates().getInfo()
var x = coors[0]
var y = coors[1];
Map.setCenter(x, y, 10);
// Elaborating the dates
// Getting Temperatures for Every Month
var period = ['-01-01', '-12-01'];
var years = [['1999', '2000'],
['2000', '2001'],
['2001', '2002'],
['2002', '2003'],
['2003', '2004'],
['2004', '2005'],
['2005', '2006'],
['2006', '2007'],
['2007', '2008'],
['2008', '2009'],
['2009', '2010'],
['2010', '2011'],
['2011', '2012'],
['2012', '2013'],
['2013', '2014'],
];
var add_period = function(year){
var start_date = period[0];
var end_date = period[1];
return [year[0] + start_date, year[1] + end_date];
};
var concatenate_year_with_periods = function(years, period){
return years.map(add_period);
};
var Dates = concatenate_year_with_periods(years, period);
/**********************************************************************
Landsat 7
***********************************************************************/
var visualization = {
bands: ['B4', 'B3', 'B2'],
min: 0.0,
max: 0.3,
};
var visualization_ = {
bands: ['B4_median', 'B3_median', 'B2_median'],
min: 0.0,
max: 0.3,
gamma: [0.95, 1.1, 1]
};
// Applies scaling factors.
var cloudMaskL7 = function(image) {
var qa = image.select('BQA');
var cloud = qa.bitwiseAnd(1 << 4)
.and(qa.bitwiseAnd(1 << 6))
.or(qa.bitwiseAnd(1 << 8));
var mask2 = image.mask().reduce(ee.Reducer.min());
return image
//.select(['B3', 'B4'], ['Red', 'NIR'])
.updateMask(cloud.not()).updateMask(mask2)
.set('system:time_start', image.get('system:time_start'));
};
var dataset = ee.ImageCollection('LANDSAT/LE07/C01/T1_TOA')
.filterDate('1999-01-01', '2020-12-31')
.filterBounds(aoi)
//.map(applyScaleFactors)
.map(cloudMaskL7)
.map(function(image){return image.clip(aoi)});
// Creating composites using median pixel value
var median_yearly_landsat_7 = function(start, end){
var dataset_ = dataset.filter(ee.Filter.date(start, end));
var median_yearly = dataset_.reduce(ee.Reducer.median());
return median_yearly;
};
var composite_name_list_l7 = ee.List([]);
var apply_monthly_composite = function(date_list){
var start = date_list[0];
var end = date_list[1];
var output_name = start + "TO" + end + "_LANSAT_7";
var composite = median_yearly_landsat_7(start, end);
composite_name_list_l7 = composite_name_list_l7.add([composite, output_name]);
Map.addLayer(composite, visualization_, output_name, false);
Export.image.toDrive({
image: composite,
description: output_name,
fileFormat: 'GeoTIFF',
crs : 'EPSG:4326',
folder : 'LANDSAT_LST_LAS_LOMAS',
region: aoi
});
return 0;
};
Dates.map(apply_monthly_composite);
/******************************************************************
// Animation gif
// Create RGB visualization images for use as animation frames.
/******************************************************************/
var text = require('users/gena/packages:text');
var annotated_collection_list = ee.List([])
var annotations = [
{position: 'left', offset: '0.25%', margin: '0.25%', property: 'label', scale: 1.5} //large scale because image if of the whole world. Use smaller scale otherwise
];
var create_annotated_collection = function(image_and_id) {
var img = image_and_id[0];
var image_id = image_and_id[1];
console.log(img);
console.log(image_id);
var img_out = img.visualize(visualization_)
.clip(aoi)//.paint(municipalities, 'FF0000', 2)
.set({'label': image_id});
Map.addLayer(img_out);
var annotated = text.annotateImage(img_out, {}, Bayern, annotations);
annotated_collection.add(annotated);
return 0;
};
var municipalities_geom = geometry;
var n = composite_name_list_l7.size().getInfo();
print(n);
for (var i = 0; i < n; i++) {
var img_info = ee.List(composite_name_list_l7.get(i));
print(img_info);
var img = ee.Image(img_info.get(0));
var img_id = ee.String(img_info.get(1));
var year = ee.String(ee.List(img_id.split("-").get(0)));
var month = ee.String(ee.List(img_id.split("-").get(1)));
var img_id_ = year.getInfo() + "_" + month.getInfo();
var img_out = img.visualize(visualization_)
.set({'label': img_id_});
var annotated = text.annotateImage(img_out, {}, municipalities_geom, annotations);
Map.addLayer(annotated);
var annotated_collection_list = annotated_collection_list.add(annotated)
}
var annotated_col = ee.ImageCollection(annotated_collection_list)
// Define GIF visualization parameters.
var gifParams = {
'region': geometry,
'dimensions': 254,
'crs': 'EPSG:32632',
'framesPerSecond': 1
};
// Print the GIF URL to the console.
print(annotated_col.getVideoThumbURL(gifParams));
// Render the GIF animation in the console.
print(ui.Thumbnail(annotated_col, gifParams));
However, this thumbnail appears black, but the images I load into the map project, are in the color visualization parameters that I need.
The geometry parameter is a Polygon I drew using the drawing tool. The coordinates are below:
Coordinates: List (1 element)
0: List (5 elements)
0: [-82.35277628512759,8.432445555054713]
1: [-82.314667459444,8.432445555054713]
2: [-82.314667459444,8.460632259476993]
3: [-82.35277628512759,8.460632259476993]
4: [-82.35277628512759,8.432445555054713]
Could someone tell my why the thumbnail appears black?

Rounded Edge Stacked Grouped Chart in amchart4

I've been looking everywhere but still can't find the answer, i have stacked and clustered chart on my website (Using amchart4), like this :
Screenshot for chart in my website
, what i want to is, round the edge of the top the chart, so chart can look like this :
Chart that have rounded corner
, I've been trying to add an adapter, base on documentation in amchart4 : https://www.amcharts.com/docs/v4/tutorials/stacked-column-series-with-rounded-corners/
but instead working like a charm, my chart look like this :
My chart Now!
where's my mistake here?
My Js Code for amchart :
am4core.ready(function() {
// Create chart instance
var chart = am4core.create('regional', am4charts.XYChart);
// Add data
chart.data = response.data;
// Create axes
var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.renderer.grid.template.disabled = true;
categoryAxis.dataFields.category = "regional";
// Room for sub-category labels
categoryAxis.renderer.labels.template.marginTop = 20;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.min = 0;
// Create series
function createSeries(field, name, stacked, color) {
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueY = field;
series.dataFields.categoryX = "regional";
series.name = name;
series.stroke = am4core.color(color);
series.fill = am4core.color(color);
// series.columns.template.tooltipText = "{name}: [bold]{valueY}[/]";
series.stacked = stacked;
series.columns.template.column.adapter.add("cornerRadiusTopLeft", cornerRadius);
series.columns.template.column.adapter.add("cornerRadiusTopRight", cornerRadius);
var bullet1 = series.bullets.push(new am4charts.LabelBullet());
bullet1.interactionsEnabled = false;
bullet1.label.text = "{valueY}";
bullet1.label.fontSize = 19;
bullet1.label.fill = am4core.color("#0d0b0b");
bullet1.locationY = 0.5;
}
// Fake series (display cluster label)
function createLabelSeries(name) {
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueY = "zero";
series.dataFields.categoryX = "regional";
series.name = name;
series.hiddenInLegend = true;
var bullet = series.bullets.push(new am4charts.LabelBullet());
bullet.label.text = "{name}";
bullet.label.hideOversized = false;
bullet.label.paddingTop = 30;
}
// Corner
function cornerRadius(radius, item) {
var dataItem = item.dataItem;
// Find the last series in this stack
var lastSeries;
chart.series.each(function(series) {
if (dataItem.dataContext[series.dataFields.valueY] && !series.isHidden && !series.isHiding) {
lastSeries = series;
}
});
// console.log(lastSeries.name);
// If current series is the one, use rounded corner
return dataItem.component == lastSeries ? 10 : radius;
}
chart.maskBullets = false;
createLabelSeries("OPEN");
createSeries("NCR_OPEN", "NCR OPEN", true, "#ff955c");
createSeries("HCR_OPEN", "HCR OPEN", true, "#ff7429");
createSeries("PCR_OPEN", "PCR OPEN", true, "#fa4300");
createLabelSeries("CLOSE");
createSeries("NCR_CLOSE", "NCR CLOSE", true, "#8870ff");
createSeries("HCR_CLOSE", "HCR CLOSE", true, "#5d3dff");
createSeries("PCR_CLOSE", "PCR CLOSE", true, "#370fff");
// Legend
chart.legend = new am4charts.Legend();
})

Issue in drawing multi value axes line chart

I am trying to create stock chart of stockprice, revenue, visits using amcharts, but m stuck while creating revenue line on it, this is the graph m getting
i want yellow line of above graph like the blue line of below graph
The code of above graph is
var sp = JSON.parse('<?php echo $graphDetails; ?>');
// for(var stkpr in sp){
// sp[stkpr].date = new Date(sp[stkpr].date);
// }
console.log(sp);
var chart;
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = sp;
chart.categoryField = "date";
// listen for "dataUpdated" event (fired when chart is inited) and call zoomChart method when it happens
chart.addListener("dataUpdated", zoomChart);
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true; // as our data is date-based, we set parseDates to true
categoryAxis.minPeriod = "DD"; // our data is daily, so we set minPeriod to DD
categoryAxis.minorGridEnabled = true;
categoryAxis.axisColor = "#DADADA";
categoryAxis.twoLineMode = true;
categoryAxis.dateFormats = [{
period: 'fff',
format: 'JJ:NN:SS'
}, {
period: 'ss',
format: 'JJ:NN:SS'
}, {
period: 'mm',
format: 'JJ:NN'
}, {
period: 'hh',
format: 'JJ:NN'
}, {
period: 'DD',
format: 'DD'
}, {
period: 'WW',
format: 'DD'
}, {
period: 'MM',
format: 'MMM'
}, {
period: 'YYYY',
format: 'YYYY'
}];
// first value axis (on the left)
var valueAxis1 = new AmCharts.ValueAxis();
valueAxis1.axisColor = "#FF6600";
valueAxis1.axisThickness = 2;
valueAxis1.gridAlpha = 0;
chart.addValueAxis(valueAxis1);
// second value axis (on the right)
var valueAxis2 = new AmCharts.ValueAxis();
valueAxis2.position = "right"; // this line makes the axis to appear on the right
valueAxis2.axisColor = "#FCD202";
valueAxis2.gridAlpha = 0;
valueAxis2.axisThickness = 2;
// categoryAxis.autoGridCount = false;
// categoryAxis.gridCount = chartData.length;
// categoryAxis.gridPosition = "start";
chart.addValueAxis(valueAxis2);
// third value axis (on the left, detached)
valueAxis3 = new AmCharts.ValueAxis();
valueAxis3.offset = 50; // this line makes the axis to appear detached from plot area
valueAxis3.gridAlpha = 0;
valueAxis3.axisColor = "#B0DE09";
valueAxis3.axisThickness = 2;
chart.addValueAxis(valueAxis3);
// GRAPHS
// first graph
var graph1 = new AmCharts.AmGraph();
graph1.valueAxis = valueAxis1; // we have to indicate which value axis should be used
graph1.title = "Stock Price";
graph1.valueField = "stockPrice";
graph1.bullet = "round";
graph1.hideBulletsCount = 30;
graph1.bulletBorderThickness = 1;
chart.addGraph(graph1);
// second graph
var graph2 = new AmCharts.AmGraph();
graph2.valueAxis = valueAxis2; // we have to indicate which value axis should be used
graph2.title = "revenue";
graph2.valueField = "revenue";
graph2.bullet = "square";
graph2.hideBulletsCount = 30;
graph2.bulletBorderThickness = 1;
chart.addGraph(graph2);
// third graph
var graph3 = new AmCharts.AmGraph();
graph3.valueAxis = valueAxis3; // we have to indicate which value axis should be used
graph3.valueField = "visits";
graph3.title = "visits";
graph3.bullet = "triangleUp";
graph3.hideBulletsCount = 30;
graph3.bulletBorderThickness = 1;
chart.addGraph(graph3);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorAlpha = 0.1;
chartCursor.fullWidth = true;
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chart.addChartScrollbar(chartScrollbar);
// LEGEND
var legend = new AmCharts.AmLegend();
legend.marginLeft = 110;
legend.useGraphSettings = true;
chart.addLegend(legend);
// WRITE
chart.write("chartdiv");
});
// this method is called when chart is first inited as we listen for "dataUpdated" event
function zoomChart() {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
chart.zoomToIndexes(5, 245);
}

dimple js x-axis date issue with bar chart

My bar chart bars on x-axis is adding to the right positions but the x-axis ticks are duplicating month and year in the dimple js. How can I adjust the x-axis as I have only three values in this data? Here is the jfiddle: http://jsfiddle.net/Ra2xS/17/
Any suggestions?
var dim = {"width":590,"height":450}; //chart container width
var data = [{"date":"01-02-2010","cost":"11.415679194952766"},{"date":"01-03-2010","cost":"10.81875691467018"},{"date":"01-04-2010","cost":"12.710197879070897"}];
function barplot(id,dim,data)
{
keys = Object.keys(data[0]);
var xcord = keys[0];
var ycord = keys[1];
var svg = dimple.newSvg(id, dim.width, dim.height);
var myChart = new dimple.chart(svg,data);
myChart.setBounds(60, 30, 505, 305);
//var x = myChart.addCategoryAxis("x", xcord);
var x = myChart.addTimeAxis("x", xcord, "%d-%m-%Y","%b %Y");
x.addOrderRule(xcord);
x.showGridlines = true;
var y = myChart.addMeasureAxis("y", ycord);
y.showGridlines = true;
y.tickFormat = ',.1f';
var s = myChart.addSeries(null, dimple.plot.bar);
var s1 = myChart.addSeries(null, dimple.plot.line);
s1.lineWeight = 3;
s1.lineMarkers = true;
myChart.draw(1500);
}
barplot("body",dim,data);
You can prevent the excess ticks/labels by setting the time period for the axis to months:
x.timePeriod = d3.time.months;
Complete demo here.

AmCharts - graphs connected by starting and ending points

I have multiple graphs per chart and for some unknown(to me) reason each graph is connected by the start and the end points of it e.g.
Simple question: How to remove it? I couldn't find anything in the documentation that controls it.
My code as follows:
lineChart = function(id, period) {
var chart, data = [];
var cData = chartData[id];
AmCharts.ready(function() {
for (item in cData) {
var i = cData[item];
data.push({
date: new Date(i.date),
impressions: i.impressions,
clicks: i.clicks,
conversions: i.conversions,
ctr: i.ctr,
profit: i.profit,
cost: i.cost,
revenue: i.revenue
});
}
chart = new AmCharts.AmSerialChart();
chart.dataProvider = data;
chart.categoryField = "date";
chart.balloon.color = "#000000";
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.fillAlpha = 1;
categoryAxis.fillColor = "#FAFAFA";
categoryAxis.gridAlpha = 0;
categoryAxis.axisAlpha = 0;
categoryAxis.minPeriod = period;
categoryAxis.parseDates = true;
categoryAxis.gridPosition = "start";
categoryAxis.position = "bottom";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.dashLength = 5;
valueAxis.axisAlpha = 0;
valueAxis.integersOnly = true;
valueAxis.gridCount = 10;
chart.addValueAxis(valueAxis);
// GRAPHS
// Impressions graph
var graph = new AmCharts.AmGraph();
graph.title = "Impressions";
graph.valueField = "impressions";
graph.balloonText = "[[title]]: [[value]]";
//graph.lineAlpha = 1;
graph.bullet = "round";
chart.addGraph(graph);
// Clicks graph
var graph = new AmCharts.AmGraph();
graph.title = "Clicks";
graph.valueField = "clicks";
graph.balloonText = "[[title]]: [[value]]";
graph.bullet = "round";
chart.addGraph(graph);
// Conversions graph
var graph = new AmCharts.AmGraph();
graph.title = "Conversion";
graph.valueField = "conversions";
graph.balloonText = "[[title]]: [[value]]";
graph.bullet = "round";
chart.addGraph(graph);
// LEGEND
var legend = new AmCharts.AmLegend();
legend.markerType = "circle";
chart.addLegend(legend);
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorPosition = "mouse";
if(period == 'hh')
chartCursor.categoryBalloonDateFormat = "MMM DD, JJ:00";
chart.addChartCursor(chartCursor);
// WRITE
chart.write(id);
});
};
This looks like the data issue. Make sure your data points are strictly in consecutive ascending order.
To verify how your actual data looks like, add the second line below to your code. Then run your chart in Google Chrome with Console open (F12 then select Console tab)
chart.dataProvider = data;
console.debug(data);
Check the datapoints for irregularities. Especially the last two ones.
The problem was that each chart was rendered within it's own AmCharts.ready method. The documentation states that it's allowed, however it didn't work for me, therefore I wrapped all rendering within one ready method and the issue was fixed.

Categories