Friday, 15 August 2014

r - Changing default ggplot2 scale inside a function -



r - Changing default ggplot2 scale inside a function -

i developing bundle contains plotting function uses ggplot2. want alter colours default scales, without affecting global environment. assigning new function scale_colour_continuous, new set of default colours.

library(ggplot2) dat <- data.frame(a = 1:5, b = 1:5) home.plot <- function(x){ scale_colour_continuous <- function(...) ggplot2::scale_colour_continuous(..., low = "purple", high = "green") ggplot(dat, aes(x = a, y = b)) + geom_point(aes(colour = a), size = 10) } home.plot(dat)

this not work , colours not changed black , bluish violet , green. guess because ggplot2 looks scale_colour_continuous() function outside of environment of home.plot function.

if seek same in global environment works:

scale_colour_continuous <- function(...) ggplot2::scale_colour_continuous(..., low = "purple", high = "green") ggplot(dat, aes(x = a, y = b)) + geom_point(aes(colour = a), size = 10)

but changes behaviour of ggplot subsequent plots , not created home.plot.

i aware can alter colours after ggplot object has been created + scale_colour_continuous(), home.plot not know if user plotted discrete or continuous variable , hence need alter behaviour of scales before ggplot object created.

any help appreciated.

dat <- data.frame(a = 1:5, b = 1:5) home.plot <- function(x,y=1){ gg <- ggplot(dat, aes(x = a, y = b)) + geom_point(aes(colour = a), size = 10) if(y==1){ gg <- gg+scale_colour_gradient(low="purple", high="green") }else{ gg <- gg+scale_colour_gradientn(colours=c("red","yellow", "green","cyan","blue")) } return(gg) } home.plot(dat)

home.plot(dat,2)

this should work. 2 colors can utilize gradient, bur multiple need gradientn

r ggplot2

No comments:

Post a Comment