Reputation: 3796
I can easily set a parameter for factor levels that can be reused multiple times as in the example below:
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))
Can I also do this with the a ggplot scale? I would like to set scale_y_continuous(scale_y_parameter) so that the scale_y_continuous parameters could be easily updated across a series of plots.
This code works:
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)
)
This is the code I'd like to work, but don't know how to set the parameter:
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)
Any help is greatly appreciated.
Upvotes: 0
Views: 169
Reputation: 214957
Store the parameters in a list, then you can either hard coding the parameters into the function:
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)
Or use do.call
to apply the list of parameters to 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)
both give:
Upvotes: 1