如何重构重复的ggplot设置



重构这些反复出现的情节设置的最佳方法是什么?我试着写一个函数来返回这些东西。但没有成功。在R中做这个的最好方法是什么?

下面是一个示例代码:
ggplot(df.offer_stats.timeworks.accepted, aes(x=time_rate)) +
geom_histogram(aes(y=..density..),color="black", fill="#009E73", alpha=.5, binwidth = 1) +
scale_x_continuous(breaks=seq(9,35,1)) +
geom_density(alpha=.3, fill="#009E73", adjust=2, trim = TRUE) +
ggtitle("Distribution of accepted timework offers") +
xlab("Stundenlohn (Verrechnung)") +
ylab("Verteilung") +
theme(
axis.text = element_text(size = 15),
axis.title.x = element_text(size = 20, vjust = - 0.5),
axis.title.y = element_text(size = 20, vjust = 1.5),
plot.title = element_text(size = 35, vjust = 1.5,face = "bold")
)

应该是这样的:-):

ggplot(df.offer_stats.timeworks.accepted, aes(x=time_rate)) +
geom_histogram(aes(y=..density..),color="black", fill="#009E73", alpha=.5, binwidth = 1) +
scale_x_continuous(breaks=seq(9,35,1)) +
geom_density(alpha=.3, fill="#009E73", adjust=2, trim = TRUE) +
plot_standard('title','xlab','ylab')

我使用了这个解决方案::-)

plot_standard <- function(title, xlab, ylab){
return(
list(
  theme(
    axis.text = element_text(size = 15),
    axis.title.x = element_text(size = 20, vjust = - 0.5),
    axis.title.y = element_text(size = 20, vjust = 1.5),
    plot.title = element_text(size = 35, vjust = 1.5,face = "bold")
    ),
    ggtitle(title),
    xlab(xlab),
    ylab(ylab))
  )

}

最新更新