[英]Set a parameter for scale in multiple ggplots
我可以轻松地为因子水平设置一个参数,该参数可以多次重复使用,如下例所示:
am_labels_parameter <- c("auto", "manual")
d <-
mtcars %>%
mutate(
cyl = as.factor(cyl),
am = factor(am, labels = am_labels_parameter)
) %>%
group_by(cyl, am) %>%
summarise(mpg = mean(mpg))
我也可以使用ggplot标度执行此操作吗? 我想设置scale_y_continuous(scale_y_parameter),以便scale_y_continuous参数可以在一系列绘图中轻松更新。
此代码有效:
d %>%
ggplot(aes(x = cyl, y = mpg, fill = am)) +
geom_col(position = "dodge") +
scale_y_continuous(
breaks = seq(0, 30, by = 10),
limits = c(0, 30)
)
这是我想要的代码,但是不知道如何设置参数:
scale_y_parameter <-
c(breaks = seq(0, 30, by = 10),
limits = c(0, 30))
d %>%
ggplot(aes(x = cyl, y = mpg, fill = am)) +
geom_col(position = "dodge") +
scale_y_continuous(scale_y_parameter)
任何帮助是极大的赞赏。
将参数存储在列表中,然后可以将参数硬编码到函数中:
scale_y_parameter <-
list(breaks = seq(0, 30, by = 10),
limits = c(0, 30))
d %>%
ggplot(aes(x = cyl, y = mpg, fill = am)) +
geom_col(position = "dodge") +
scale_y_continuous(breaks = scale_y_parameter$breaks, limits = scale_y_parameter$limits)
或使用do.call
将参数列表应用于scale_y_continuous
:
scale_y_parameter <-
list(breaks = seq(0, 30, by = 10),
limits = c(0, 30))
d %>%
ggplot(aes(x = cyl, y = mpg, fill = am)) +
geom_col(position = "dodge") +
do.call(scale_y_continuous, scale_y_parameter)
两者都给:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.