Monday 10 March 2014

My first plot with xkcd

  xkcd R package is a tool to enhance the R plot. Usually, I use ggplot2 to build my plot, but I wanted to create "more informal" plot so I found this library [2].


1) Install the extrafont e xkcd and sysfonts packages (I have had some problem with update packages, so before I have run

update.packages(checkBuilt = TRUE, ask = FALSE)


And then install xkcd from R repository and extrafont from downloaded code. The sysfonts required to install free-type (sudo apt-get install freetype*)


 2) Install fonts from http://simonsoftware.se/other/xkcd.ttf within the R console


library(ggplot2)
library(extrafont)
 if(! "xkcd" %in% fonts()) {

xkcdFontURL <- "http://simonsoftware.se/other/xkcd.ttf"
download.file(xkcdFontURL,dest="xkcd.ttf")
font_import(".")
 ## because we downloaded to working directory

loadfonts()

}



3) Install ggplot (In R)

library(ggplot2)
library(xkcd)
library(extrafont)
library(lubridate)

wind<- read.table(file = myFile, header =TRUE)
wind$date<-as.character(datiVento$date)
wind$date<-ymd(wind$date)
wind$doy<-yday(wind$date)
p<-ggplot(wind,aes(wind$doy,wind$media))+geom_point()+xkcdaxis(range(c(1,366)),range(c(1,20)))+facet_wrap(~
 station)+ylab("velocita' [m/s]")+xlab("day of year")
 
ggsave(myOutFile)


And to obtain a bar plot of the speed class:
wind<-wind[wind$stazione=='myStation',]
scalaBeaufort<-c(0.0,0.3,1.5,3.4,5.4,7.9,10.7,13.8,17.1,20.7,24.4,28.4,32.6,50)
wind$speedClass<-NA
n&lt-13
for(i in 1:n){
    inf&lt-scalaBeaufort[i]
    sup&lt-scalaBeaufort[i+1]
    wind[!is.na(wind$media) & wind$media >=inf &  wind$media < sup,c("speedClass")]<&lt-i-1
}

freqWind<-table(wind$speedClass)
freqWind<-data.frame(y=as.numeric(freqWind),x=as.numeric(names(freqWind)))
freqWind$xmin <- freqWind$x - 0.1
freqWind$xmax <- freqWind$x + 0.1
freqWind$ymin <- 0
freqWind$ymax <- freqWind$y

xrange<-range(c(-0.1,3))
yrange<-range(c(0,350))

mapping<-aes(xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax)
p<-ggplot()+themexkcd()+ xkcdrect(mapping,freqWind)+
xkcdaxis(xrange,yrange)+scale_x_discrete(breaks = 0:2, labels=c("0","1","2")) +
xlab(NULL)




4)Next step working with map...


 references 
  1.  R http://www.r-project.org/
  2.  xkcd - http://xkcd.r-forge.r-project.org/
  3.  ggplot2 - http://ggplot2.org/
  4.  lubridate - http://cran.r-project.org/web/packages/lubridate/index.html

No comments:

Post a Comment