我是一个懒惰的家伙,所以我不想一次又一次地输入相同的代码(甚至不复制和粘贴:P)。我想知道是否可以编写一个函数来返回一些文本字符串作为公式,所以下次,当我想要使用这一套赞誉时,我可以调用该函数,将自动粘贴整段代码。
例如,这一次,我使用ggplot2
制作了一些箱形图,我想对我的情节进行一些自定义。所以我有
ggplot(abc, aes(group, abcabc))+geom_boxplot(aes(fill=group)) +
geom_hline(yintercept=0, color="grey") +
theme(panel.background=element_rect(fill = "white")) +
scale_fill_manual(values = c("white", "white"))
您可以看到最后两行代码正在进行一些格式化设置。每次我想以这种格式生成一个箱形图时,我都可以使用这两行代码。如果我可以编写一个可以将这两行代码作为公式返回的函数,我可以在将来ggplot
中将该函数用作某种主题。所以我试着编写一个这样的函数:
box.format<-function(){
return(as.formula('theme(panel.background=element_rect(fill = "white")) + scale_fill_manual(values = c("white", "white"))'))
}
但是,我收到了这样的消息:
错误:不知道如何将scale_fill_manual(values = c(&#34; white&#34;,&#34; white&#34;))添加到主题对象
有谁知道如何修复此错误,还是有其他方法可以解决此问题?
答案 0 :(得分:0)
我想你可以尝试关闭。下面是一个快速试用,虽然没有完全测试。理想情况下,您应该能够使用闭包创建自己的函数工厂。
mygg <- function(...) {
function(data, x, y) {
ggplot(data, aes(x, y))+geom_boxplot(aes(fill=x)) +
geom_hline(yintercept=0, color=color_param) +
theme(panel.background=element_rect(fill = back_param)) +
scale_fill_manual(values = c(scale_param_x, scala_param_y))
}
}
gg <- mygg(color_param = "grey", back_param = "white", scale_param_x = "white", scale_param_y = "white")
gg
function(data, x, y) {
ggplot(data, aes(x, y))+geom_boxplot(aes(fill=x)) +
geom_hline(yintercept=0, color=color_param) +
theme(panel.background=element_rect(fill = back_param)) +
scale_fill_manual(values = c(scale_param_x, scala_param_y))
}
<environment: 0x0000000018d7cea0>