0

我现在正在创建很多情节。由于它们都针对相同的演示文稿,因此在我选择赋予它们外观的选项方面,它们有很多共同点。

df1 <- data.frame(name = c("name1","name2","name3","name4"),
                  variable = c("var1","var1","var2","var2"),
                  value = c(15,16,17,18))

df1 %>%
  ggplot(aes(x = name, y = value, fill = variable)) +
  geom_bar(stat = "identity", position = position_stack()) +
  labs(title = "Plot Title",
       subtitle = "month 1",
       x="",
       y="Count") +
  scale_fill_viridis_d(name = "", option = "inferno", begin = 0.3, end = 0.7, direction = -1) +
  scale_shape_tableau() +
  theme_economist() +
  theme(plot.background = element_rect(fill = "white"), 
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1),
        plot.margin = unit(c(1,1,1,1), "cm"))

以减少代码行数的心态,有没有办法用其中的一些选项创建一个函数,比如“theme”、“theme_economist”、“scale_shape”、“scale_fill”?然后我可以为每个情节指定美学和实验室,其余的只是一个“+预设功能”,以添加主题、颜色和形状。

4

1 回答 1

2

您可以将要添加到绘图中的内容存储在列表中。然后,您可以通过将其添加到绘图来重新使用此列表。

library(ggplot2)
library(ggthemes)
library(magrittr)

common_options <- list(
  scale_fill_viridis_d(name = "", option = "inferno", begin = 0.3, end = 0.7, direction = -1),
  scale_shape_tableau(),
  theme_economist(),
  theme(plot.background = element_rect(fill = "white"), 
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5),
        axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1),
        plot.margin = unit(c(1,1,1,1), "cm"))
)



df1 <- data.frame(name = c("name1","name2","name3","name4"),
                  variable = c("var1","var1","var2","var2"),
                  value = c(15,16,17,18))

df1 %>%
  ggplot(aes(x = name, y = value, fill = variable)) +
  geom_bar(stat = "identity", position = position_stack()) +
  labs(title = "Plot Title",
       subtitle = "month 1",
       x="",
       y="Count") +
  common_options

reprex 包于 2021-07-20 创建(v1.0.0)

于 2021-07-20T07:08:26.783 回答