r - Why is theme created returned by a function delayed in its application? -


in following example function returns theme, altered extend (in minimum example extreme ugly modifications...). adding function first time ggplot not anything, adding further plot works intenden. how can make sure, function works alreay in first application, or error in thinking?

require(ggplot2)  # minimal example: function returning theme modifications mytheme <- function(size = 3) {   th.my <- theme_set(theme_bw(base_size=size))   th.my$axis.ticks$size = 1   return (th.my) }  # plot something, applying theme function first time fig1 <- ggplot(data = mtcars, aes(x = mpg)) +         geom_point(aes(y = hp)) +         mytheme() print(fig1)  # same, again fig2 <- ggplot(data = mtcars, aes(x = mpg)) +         geom_point(aes(y = hp)) +         mytheme() print(fig2) 

as 1 can see in following plots, first time theme not applied, second time worked...

so far, not working! now works...

this because theme_set changes default future calls ggplot, not change "current" theme. if create own theme function, should return list of changes. don't bother theme_set. should work

mytheme <- function(size = 3) {     theme_bw(base_size=size) + theme(axis.ticks= element_line(size = 1)) }  ggplot(data = mtcars, aes(x = mpg)) +     geom_point(aes(y = hp)) +     mytheme() 

or if wanted these themes apply future plots, run

theme_set(mytheme()) ggplot(data = mtcars, aes(x = mpg)) +     geom_point(aes(y = hp)) # note don't need add plot time since we've # set default 

Comments

Popular posts from this blog

c# - Where does the .ToList() go in LINQ query result -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -