如何重构经常性的ggplot设置?

时间:2015-09-02 10:12:52

标签: r ggplot2 refactoring

重构那些经常性情节设置的最佳方法是什么?我试着编写一个函数来返回这些东西。它没有用。 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')

1 个答案:

答案 0 :(得分:1)

我用过这个解决方案:: - )

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

}