How to make nvd3 json format with R

With nvd3 it is possible to create nice interactive line charts. The required json format can be generated with R.

Click here to see the chart.

The origin data, which we use here, was downloaded from the EEX Transparency Platform. It contains the actual and expected solar power generation of Germany for Thursday, 2014-09-04. This data was created by simply calculating the sum of production from the four German TSOs (TenneT, 50Hertz, Amprion, TransnetBW) and converting the time to a numeric JavaScript Date.

# Download data
url.c='http://climvis.de/wp-content/uploads/nvd3/R/json-data.csv'
dfile='json-data.csv'
download.file(url.c, destfile=dfile, method='wget')

# Read data
idat=read.csv(dfile, head=T, sep=';')

To use the function DatToJson the coordinates of each line has to be in a R-list.

# dat for function DatToJson
dat=list()
dat[[1]]=idat[,c(1,2)]
dat[[2]]=idat[,c(1,3)]
dat[[3]]=idat[,c(1,4)]
names(dat)=c('Observation [MW]','Prediction [MW]','Difference [MW]')

In the next step, we download, load and use the function DatToJson.

# Download function DatToJson
url.c='http://climvis.de/wp-content/uploads/nvd3/R/DatToJson.R'
dfile='DatToJson.R'
download.file(url.c, destfile=dfile, method='wget')

# Load function DatToJson
source('DatToJson.R')

# Create json with DatToJson
json=DatToJson(dat)

Finally, we write the data.json file so we can use it with JavaScript.

# Write json
write.table(json,'data.json', row.names=F, quote=F, col.names=F)

To see how you can insert the line chart into a website look at index.html.