John
John

Reputation: 5239

R: ggplot2, how to add a number of layers to a plot at once to reduce code

library(ggplot2)

This code produces a nice looking plot:

qplot(cty, hwy, data = mpg, colour = displ) +
scale_y_log2() + 
labs(x="x axis") + 
labs(y="y axis") +
opts(title = "my title")

But I want to setup variables to try and to reduce code repetition:

log_scale <- scale_y_log2()
xscale <-   labs(x="x axis")
yscale <-   labs(y="y axis") 
title <- opts(title = "my title")
my_scales <- c(log_scale, xscale, yscale, title) 
# make a variable to hold the scale info changes above

So that I can do this and add a bunch of things at the same time:

qplot(cty, hwy, data = mpg, colour = displ) + my_scales  
# add these to your plot.   

but I get this error:

Error in object$class : $ operator is invalid for atomic vectors

I realize that the things going into my_scales need to be layers / different types of objects, but I don't see what they should be.

Upvotes: 3

Views: 1009

Answers (1)

hadley
hadley

Reputation: 103898

Use a list:

my_scales <- list(log_scale, xscale, yscale, title) 

Upvotes: 4

Related Questions