Reputation: 13850
Lets say I've made three plots with this code:
library(ggplot2)
ggplot(mtcars, aes(hp, wt, color = as.factor(cyl))) + geom_point() + scale_color_manual(limits = c("4", "6", "8"), breaks = c("4", "6", "8"), values = c("red", "blue", "green"))
ggplot(mtcars, aes(hp, mpg, color = as.factor(cyl))) + geom_point() + scale_color_manual(limits = c("4", "6", "8"), breaks = c("4", "6", "8"), values = c("red", "blue", "green"))
ggplot(mtcars, aes(hp, drat, color = as.factor(cyl))) + geom_point() + scale_color_manual(limits = c("4", "6", "8"), breaks = c("4", "6", "8"), values = c("red", "blue", "green"))
How can I convert this part of the code to a function called: scale_color_manual(limits = c("4", "6", "8"), breaks = c("4", "6", "8"), values = c("red", "blue", "green"))?
Upvotes: 0
Views: 118
Reputation: 20811
You could take advantage of %+%
library(ggplot2)
p1 <- ggplot(mtcars, aes(hp, wt, color = as.factor(cyl))) +
geom_point() +
scale_color_manual(limits = c("4", "6", "8"),
breaks = c("4", "6", "8"),
values = c("red", "blue", "green"))
p2 <- aes(hp, mpg, color = as.factor(cyl))
p1 %+% p2
p3 <- aes(hp, drat, color = as.factor(cyl))
p1 %+% p3
EDIT
or you can define your scale like:
my_scale <- scale_color_manual(limits = c("4", "6", "8"),
breaks = c("4", "6", "8"),
values = c("red", "blue", "green"))
and
p1 <- ggplot(mtcars, aes(hp, wt, color = as.factor(cyl))) + geom_point()
p1 + my_scale
Upvotes: 3