0

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"))?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

rawr thats a nice idea but it wouldn't work in my circumstances
@luciano why not? Could you expand your question to make more clear what you really need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.