我今天终于搞清楚了这个问题。不过是因为遇到了另一个问题而搞明白的。并不是ggtitle()
的问题,这就是个歪打正着的故事……
今天想对统计图的标题字号进行调整,经搜索发现通用的处理方法是theme(plot.title = element_text(size=40))
,其中数字按需修改。但是写上这句话以后,标题又消失了。
这两次消失让我意识到,这并不是无法居中或者无法调整字号的问题,而是一添加theme函数整个标题就消失了的问题。但是这个问题的出现非常不符合逻辑,逼着我一遍又一遍地看自己的代码(出于示意目的做了部分简化修改):
draw_graph<-function(i, m)
{
# Prepare the dataset
pattern=c("xxx"="#.$", "yyy"="p.?$")
dataset=filter(original, Variable==i, grepl(pattern[m], Condition))
# Graph title
title=ggtitle(paste("The distribution of", i, "under the impacts of the", m))
size=c(18, 18, 10, 10, 10, 18)
title=title+theme(plot.title=element_text(size = size[i], hjust=0.5))
# Graph style
style=geom_density(stat="bin", bins=200, size=0.3, alpha=0.3)
# Reference lines
ref=c(35, 50, 100, 200, 100, 180)
ref_lines=geom_vline(aes(xintercept=ref[i]), color="grey50", linetype="solid")
# Mean lines
dataset %>% group_by(Condition, Treatment, Behaviour) %>% summarize(Mean=mean(Hits)) %>% geom_vline(data=., aes(xintercept=Hits, color=Behaviour), linetype="longdash" ) -> mean_lines
# Faceting
facets=facet_grid(Condition~Treatment)
# Draw graph
graph=ggplot(dataset, aes(x=Hits, y=..density.., group=Behaviour, color=Behaviour, fill=Behaviour))+style+title+facets+ref_lines+mean_lines
# Save graph
ggsave(paste(file_path, i, " ", m, ".png", sep=""), plot=graph, device="png", width=30, height=18, units="cm", dpi=600)
}
因为数据维度较多,所以作图过程比较复杂,为了清楚,把ggplot
的很多成分分开写的。
经同学研究指点,我今天才发现的是ggplot
可以用+
添加不同的成分,但是这并不意味着这些成分之间也可以用+
连接。上面的例子中这一行有错:
title=title+theme(plot.title=element_text(size = size[m], hjust=0.5))
我本来很自然地把标题和对于标题位置和字号的修饰放在了一起,因为形如ggplot()+geom_xxx()
这样的用法非常常见。但实际上ggtitle()
的返回对象作为一个相对次要的组成部分,并不能再通过+
连接其他部分。这么做的话破坏了ggtitle()
的返回对象,所以标题消失了,而我原本希望的位置和字号的改变也实现不了。这一点,其实在我最初开这个帖子的时候已经描述了,但是我当时意识不到:
Heterogeneity (3)使用labs(title=...)+theme(plot.title = element_text(hjust = 0.5)),想把总标题居中放置。但是这种方法是失败的,总标题会消失。
同理可证,如果其它的次要组成对象之间用+
连接的话,也都会消失或者报错。
Liechi 的帖子里,绘图部分的结构是ggplot()+geom_point()+facet_wrap()+labs()+theme()
,是在主要成分上添加次要成分,所以不会出现问题。
解决方案也很简单,把ggtitle()
和theme()
分开写再加到ggplot()
上就没问题了:
.
.
.
# Graph title
title=ggtitle(paste("The distribution of", i, "under the impacts of the", m))
size=c(18, 18, 10, 10, 10, 18)
theme=theme(plot.title=element_text(size = size[i], hjust=0.5))
.
.
.
# Draw graph
graph=ggplot(dataset, aes(x=Hits, y=..density.., group=Behaviour, color=Behaviour, fill=Behaviour))+style+title+theme+facets+ref_lines+mean_lines
.
.
.