Formatting currency when exporting amCharts - format

I'm working with amCharts 3.20.9, I sucesfully draw a graph and may export the data into an XLSX file. However, one of the columns I'm exporting is a currency, is there a way of setting such a format in the resulting file?
The script I have for the graph is:
var chart = AmCharts.makeChart("graph", {
"type" : "serial",
"theme" : "light",
"dataProvider" : data,
"valueAxes" : [ {
"stackType": "regular",
"gridColor" : "#FFFFFF",
"gridAlpha" : 0.2,
"dashLength" : 0,
"title" : "Metros cúbicos"
} ],
"gridAboveGraphs" : true,
"startDuration" : 1,
"graphs" : graphs,
"chartCursor" : {
"categoryBalloonEnabled" : false,
"cursorAlpha" : 0,
"zoomable" : false
},
"categoryField" : "formatedTime",
"categoryAxis" : {
"gridPosition" : "start",
"gridAlpha" : 0,
"tickPosition" : "start",
"tickLength" : 20,
"parseDates" : false,
"labelsEnabled": true,
"labelFrequency": 3
},
"export" : {
"enabled" : true,
"fileName" : "Reporte",
"exportTitles" : true,
"exportFields" : fields,
"columnNames" : columnNames,
"menu" : [ {
"class" : "export-main",
"menu" : [ "PDF", "XLSX" ]
} ]
}
});
Where:
graphs contains the graphs definitions, something like:
[{
"balloonText" : "[[formatedTime]]: <b>[[" + sites[i] + "]]</b>",
"balloonFunction" : formater,
"lineThickness": 1,
"lineAlpha" : 0.2,
"type" : "line",
"valueField" : sites[i]
}];
fields: ["formatedTime", "Viva Villavicencio", "Viva Villavicencio_COST_"]
columnNames: {"formatedTime": "Fecha", "Viva Villavicencio": "Metros cúbicos para: Viva Villavicencio", "Viva Villavicencio_COST_": "Costo para: Viva Villavicencio"}
So far so good, I have my xlsx with the proper data, but at the end I want the column "Viva Villavicencio_COST_" be defined as a currency in the resulting file and therefore formatted and displayed that way.
Any help will be appreciated.

Have a look at the processData option. It takes a callback function that lets you make changes to your dataset before it gets written to your exported file.
So, add to your code:
"export": {
"processData": function(data){
for(var i = 0; i < data.length; i++){
data[i].Viva Villavicencio_COST_ = toCurrency(data[i].Viva Villavicencio_COST_);
}
return data;
}
...
}
This function returns the exact dataset as before, but with a formatted Viva Villavicencio_COST_ field.
Then, add the function toCurrency. I don't believe amCharts has a function built in for formatting. If you need a better formatting function you could use something like numeral.js or accounting.js, but for now try:
function toCurrency(value){
return '$' + value;
}
Complete docs for the export plugin are here: https://github.com/amcharts/export
Hope that helps.

Related

Highlight Major Value Grid Lines

Is there a setting that I'm missing to highlight major axis grid lines? I've mocked up an example of what I'm trying to do below. The arrows point to what I want, the circle shows what I have. The axis value highlights the day of the week, but not the grid line. I have a feeling that it is considering the 12 pm's as major axis grid lines too.
Here is what I have for the categoryAxis:
"categoryAxis" :
{
"equalSpacing" : true,
"minPeriod" : "hh",
"parseDates" : true,
"fontSize" : 24,
"dateFormats" : [
{
period : 'fff',
format : 'JJ:NN:SS'
},
{
period : 'ss',
format : 'JJ:NN:SS'
},
{
period : 'mm',
format : 'JJ:NN'
},
{
period : 'hh',
format : 'L A'
},
{
period : 'DD',
format : 'MMM DD\n L A'
},
{
period : 'WW',
format : 'MMM DD\n L A'
},
{
period : 'MM',
format : 'MMM DD\n L A'
},
{
period : 'YYYY',
format : 'MMM DD\n L A'
}]
},
No, there isn't a setting that highlights those lines automatically. You can use a guide to highlight those times by drawing a darker line.
Typically, this is done manually, however you can use the init event to automatically do this by having it read the category axis' internal start and end dates and placing the guides as needed:
var chart = AmCharts.makeChart("chartdiv", {
// ...
"listeners": [{
"event": "init",
"method": function(e) {
//get the start and end date objects from the categoryAxis' internal data array
var startDate = new Date(e.chart.categoryAxis.data[0].category);
var endDate = new Date(e.chart.categoryAxis.data[e.chart.categoryAxis.data.length - 1].category);
var guides = [];
var guideDate;
//start at midnight
startDate.setHours(0, 0, 0, 0);
while (startDate.getTime() <= endDate.getTime()) {
guideDate = new Date(startDate);
guides.push({
"lineAlpha": 1,
"lineColor": "#000",
"date": guideDate
});
startDate.setDate(startDate.getDate() + 1);
}
//remove the first guide if it falls outside of the full date range of the axis
if (guides[0].date.getTime() < e.chart.categoryAxis.data[0].category.getTime()) {
guides.shift();
}
e.chart.categoryAxis.guides = guides;
e.chart.validateNow(); //draw the guides
}
}]
});
Demo

Setting up React in combination with NVD3

I am fairly new to React (and front-end work in general). How can I make set up React to work with NVD3?
Currently I am trying to implement the example code of react-nvd3, but get the following error thrown by the d3 function d3.transform():
Unexpected value translate(145, NaN) parsing transform attribute.
g.setAttribute("transform", string);
My code is as follows:
var TestData = [{
key: "Cumulative Return",
values: [
{
"label" : "A" ,
"value" : -29.765957771107
} ,
{
"label" : "B" ,
"value" : 0
} ,
{
"label" : "C" ,
"value" : 32.807804682612
} ,
{
"label" : "D" ,
"value" : 196.45946739256
} ,
{
"label" : "E" ,
"value" : 0.19434030906893
} ,
{
"label" : "F" ,
"value" : -98.079782601442
} ,
{
"label" : "G" ,
"value" : -13.925743130903
} ,
{
"label" : "H" ,
"value" : -5.1387322875705
}
]
}];
var App = React.createClass({
render: function() {
return (
<NVD3Chart id="chart" type="discreteBarChart" datum={TestData} x="test" y="test"/>
);
}
});
ReactDOM.render(
<App/>,
document.getElementById('container')
);
See https://jsfiddle.net/x2wuko8g/2/ I guess it has to do something with the format of TestData, but can't figure it out.
Help is much appreciated!
I think the problem is your x and y props are misconfigured.
<NVD3Chart id="chart" type="discreteBarChart" datum={TestData} x="test" y="test"/>
You set x to test and y to test but those fields are not present in your data.
Try changing x to label and y to value in this way:
<NVD3Chart id="chart" type="discreteBarChart" datum={TestData} x="label" y="value"/>
If you pass a string (like in this case) the library will look up in each item of the data for a key with that string.
I hope this help.

How to update this specific data in this user collection in mongodb?

I need to do an update to a specific soldier in this user collection:
For example:
user: {
myArmy : {
money : 100,
fans : 100,
mySoldiers : [{
_id : ddd111bbb,
mySkill : 50,
myStamina : 50,
myMoral : 50,
},
{
_id : ddd111dd ,
mySkill : 50,
myStamina : 50,
myMoral : 50,
}],
}
}
I want in my update query to do like the following:
conditions = { _id : user._id };
update =
{ 'myArmy.mySoldiers._id' : soldierId},
{
'$set': {
'myArmy.money' : balanceToSet,
'myArmy.fans' : fansToSet,
'myArmy.mySoldiers.$.skill': skillToSet,
'myArmy.mySoldiers.$.stamina': staminaToSet,
'myArmy.mySoldiers.$.moral': moralToSet
}
}
and this is the final query:
User.update(conditions, update, options, function(err){
if (err) deferred.reject;
stream.resume();
});
And the end result if soldierId is 'ddd111bbb':
user: {
myArmy : {
money : 200,
fans : 100,
mySoldiers : [{
_id : ddd111bbb,
mySkill : 150,
myStamina : 250,
myMoral : 50,
},
{
_id : ddd111dd ,
mySkill : 50,
myStamina : 50,
myMoral : 50,
}],
}
}
Those skill, moral and stamina should change only on the specific soldier.
How do i get the $ to be the index number of this soldier, what is missing from the update query above?
This is what i was looking for:
conditions = { _id : user._id , 'myArmy.mySoldiers._id' : soldierId};
update = {
$set: {
'myArmy.balance': balanceToSet,
'myArmy.fans' : fansToSet,
'myArmy.tokens' : tokensToSet,
'myArmy.mySoldiers.$.skill' : skillToSet,
'myArmy.mySoldiers.$.stamina': staminaToSet,
'myArmy.mySoldiers.$.moral' : moralToSet
}
}
This gave me the result i wanted, before i accidentally inserted the condition query with the update one...

MongoDB Data Model Optimization

About
I have raw data which is processed by aggregation framework and later results saved in another collection. Let's assume aggregation results in something like this:
cursor = {
"result" : [
{
"_id" : {
"x" : 1,
"version" : [
"2_0"
],
"date" : {
"year" : 2015,
"month" : 3,
"day" : 26
}
},
"x" : 1,
"count" : 2
}
],
"ok" : 1
};
Note that in most cases cursor length are more than about 2k elements.
So, now i'm looping thought cursor ( cursor.forEach ) and performing following steps:
// Try to increment values:
var inc = db.runCommand({
findAndModify: my_coll,
query : {
"_id.x" : "1",
"value.2_0" : {
"$elemMatch" : {
"date" : ISODate("2015-12-18T00:00:00Z")
}
}
},
update : { $inc: {
"value.2_0.$.x" : 1
} }
});
// If there's no effected row via inc operation, - sub-element doesn't exists at all
// so let's push it
if (inc.value == null) {
date[date.key] = date.value;
var up = db.getCollection(my_coll).update(
{
"_id.x" : 1
},
{
$push : {}
},
{ writeConcern: { w: "majority", wtimeout: 5000 } }
);
// No document found for inserting sub element, let's create it
if (up.nMatched == 0) {
db.getCollection(my_coll).insert({
"_id" : {
"x" : 1
},
"value" : {}
});
}}
Resulting data-structure:
data = {
"_id" : {
"x" : 1,
"y" : 1
},
"value" : {
"2_0" : [
{
"date" : ISODate("2014-12-17T00:00:00.000Z"),
"x" : 1
},
{
"date" : ISODate("2014-12-18T00:00:00.000Z"),
"x" : 2
}
]
}
};
In short i have to apply these actions to process my data:
Try to increment values.
If there's no effected data by increment operation push data to array.
If there's no effected data by push operation create new document.
Problem:
In some cases aggregation result returns more than 2k results i have to apply mentioned steps who causes performance bottleneck. While i'm processing already aggregated data, - new data accumulates for aggregation and later i cannot apply even aggregation to this new raw data because it exceeds 64MB size limit due firsts slowness.
Question:
How i can with this data-structure improve performance when increasing x ( see data-stucture ) values or adding-sub elements?
Also i cannot apply mongodb bulk operations due nested structure using positional parameter.
Maybe chosen data-model is not correct? Or maybe i'm doing not correctly aggregation task at all?
How i can improve aggregated data insertions?

Generating Different Colours On the JVectorMap Regions Based On The Range Of Values

I'm using JVectorMap for creating World Map..
As part of my JVectorMap im displaying on the regions CountryName with Population..
My Question is:
How to show differrent colours for the regions (countries) based on population ranges.
Ex: For 1-1000 population i have to show red colour.
For 1000-5000 population i have to show blue colour.
I'm using code like this.But it is not displaying different colours based on the range of population
var mapData = {
"AF": 1000,
"AL": 5000,
"DZ": 20000,
...
};
try{
$('#id').vectorMap(
{
map : 'world_mill_en',
series : {
regions : [ {
initial : {
fill : 'white',
"fill-opacity" : 1,
stroke : 'none',
"stroke-width" : 0,
"stroke-opacity" : 1
},
hover : {
"fill-opacity" : 0.8
},
selected : {
fill : 'yellow'
},
selectedHover : {},
values : mapData,
scale : [ '#C8EEFF', '#0071A4' ],
normalizeFunction : 'polynomial'
} ]
},
onRegionLabelShow : function(e, el, code) {
el.html(el.html()+' (Population - '+mapData[code]+')');
}
});
}
catch(err){
alert(err);
}
Can any one help me in displaying differnt colours for the regions based on the range of population......?
Thanks in advance..
Create a JSON with count and color codes like this according to your regions and colors.
var colorData = {
"1" : "#C8EEFF",
"2" : "#0071A4",
"3" : "#C8EEFF",
"4" : "#0071A4",
"5" : "#C8EEFF",
"6" : "#0071A4"
}
and pass this JSON to the scale : colorData. Hope it helps you.

Resources