Thursday, June 27, 2013

Calling R from GAMS to produce high quality graphs

Here is a small demo script that shows how we can call R from GAMS to produce graphs using ggplot.

* name of the R script to execute
$set rscript  my_script.R

* include file with data
$include popage.inc


execute_unload 'popage.gdx';
execute 'gdxdump popage.gdx format=csv symb=popage output=popage.csv'
;
execute 'head popage.csv'
;
execute '"C:\Program Files\R\R-2.15.0\bin\R.exe" --vanilla < %rscript%'
;

execute 'shellexecute areaplot.svg'
;
execute 'shellexecute percentplot.svg'
;


$onecho > %rscript%

popage = read.csv("popage.csv")

popage$AgeGroup = factor(popage$AgeGroup, levels = c('<5','5-14','15-24','25-34','35-44','45-54','55-64','>64'))
summary(popage)

library(ggplot2)
svg("areaplot.svg")
ggplot(popage, aes(x=Year, y=Val, fill=AgeGroup))  + geom_area() + ylab("Population (Thousands)")
dev.off()


library(plyr)
popage_percent = ddply(popage, "Year", transform, Percent = Val / sum(Val) * 100)
svg("percentplot.svg")
ggplot(popage_percent, aes(x=Year, y=Percent, fill=AgeGroup))  +
   
geom_area(colour='black', size=.2, alpha=.4) +
   
scale_fill_brewer(palette='Blues', breaks=rev(levels(popage$AgeGroup)))
dev.off()

$offecho

Results look like:

r1r2

We reproduced these graphs from from:

No comments:

Post a Comment