使用ggplot2的功能

时间:2014-03-08 20:44:17

标签: r function ggplot2

假设我用这段代码制作了三个图:

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

如何将此部分代码转换为名为:scale_color_manual(limits = c(“4”,“6”,“8”),breaks = c(“4”,“6”,“8)的函数“),值= c(”红色“,”蓝色“,”绿色“))?

1 个答案:

答案 0 :(得分:3)

您可以利用%+%

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

修改

或者您可以定义您的比例:

my_scale <-  scale_color_manual(limits = c("4", "6", "8"), 
                                breaks = c("4", "6", "8"), 
                                values = c("red", "blue", "green"))

p1 <- ggplot(mtcars, aes(hp, wt, color = as.factor(cyl))) + geom_point()

p1 + my_scale