Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Externalization of code- layout in ggplot

I would like to externalize my layouts in ggplot2 because my code gets very crowded.

Lets say I have a given layout which I apply on several plots in different functions. It looks like this:

    scale_fill_gradientn(guide="colourbar",colours=costum.colorbar_sand.blue.green)+
      theme (legend.title = element_text(size = 15,family="Arial"))+
      theme (legend.text = element_text(size = 12,family="Arial",angle=45))+
      theme (legend.position = "bottom")+
      coord_map(projection="mercator");

I would like to put it an external file or in an object and then call it into my plot function.

I tried read_chunk from the knitr package like this: I saved the blank code as it is above in an R file and then tried to implement it in my function. Therefore i just wrote it down into the function like this

    function.xy(...){...some ggplot function...
    read_chunk("some\path")
    }

But it dind't work out. I also tried paste(read_chunk("some\path")) but this dind't work eather.

Another idea I had was to save it as an object and the just paste the text but this wasn't quite working as well because i dind't figure out how to save it as a plain text object (if there is something like that). Can anyone advice me on how to do this?

like image 468
Joschi Avatar asked Feb 10 '13 20:02

Joschi


2 Answers

You can externalize the layout code into a separate chunk. See example 083 (and its output) in the knitr-examples repository. The key is chunk references via <<>>.

like image 195
Yihui Xie Avatar answered Nov 15 '22 06:11

Yihui Xie


I do this one of two ways. In my file to be knit, I declare plot options that I know are going to be used frequently, saving grouped elements in a list, like so:

plot.option1 <- list(scale_fill_gradient(guide="colourbar",colours=costum.colorbar_sand.blue.green),
                     theme(legend.title = element_text(size = 15,family="Arial"),
                           legend.text = element_text(size = 12,family="Arial",angle=45),
                           legend.position = "bottom"),
                     coord_map(projection="mercator"))

Then it's just a matter of appending + plot.option1

For example:

ggplot(dat, aes(x,y)) + plot.option1

If you have a lot of them (say for corporate themes) you can just as easily put them in a seperate script and then source it at the head of your file to be knit.

Minimal example:

plot.opt <- list(scale_color_brewer(palette="Blues"))
ggplot(diamonds, aes(carat, price, color=color)) + geom_point() + plot.opt
like image 32
Brandon Bertelsen Avatar answered Nov 15 '22 06:11

Brandon Bertelsen