似乎是这样的情况,只要我在ggplot2中调用theme(),我之前的labs()就会删除/覆盖同一个绘图。我现在冲浪了5个小时,我没有看到解决方案。有谁看到这种情况发生的原因?你会节省我的一周。
这是我的代码:
#creating variables and store them in new data frame
rel_pred <- fitted(rel)
rel_resid <- residuals(rel)
data1 <- data.frame(rel_resid, rel_pred)`
#plot the data
plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) +
geom_point() +
geom_hline(yintercept=0, colour='red') #so far so good, everything works
plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure
1. Residuals vs. fitted Values Model 1") #when I run this, it perfectly
adds labels
问题出现了:只要我用其中的任何元素运行theme(),它就会使我以前的标签消失。
plot1 + theme(panel.background = element_rect(fill='transparent'),
plot.background = element_rect(fill='transparent'),
panel.border = element_blank(),
axis.line = element_line(colour="black", size=1),
axis.title.x = element_text(colour='black',size=6),
axis.title.y = element_text(colour='black', size=6),
plot.caption = element_text('Figure 1. Residuals vs. fitted Values Model
1')
)
答案 0 :(得分:2)
正如理查德所说,你忘了“更新”plot1
作为在原始情节中添加标签的结果。
下面:
plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) +
geom_point() +
geom_hline(yintercept=0, colour='red') #so far so good, everything works
plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure
1. Residuals vs. fitted Values Model 1") #when I run this, it perfectly
adds labels
尝试改为
plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) +
geom_point() +
geom_hline(yintercept=0, colour='red') #so far so good, everything works
plot1 <- plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure
1. Residuals vs. fitted Values Model 1") # no output now, it will save the result as plot1
然后
plot1 + theme(panel.background = element_rect(fill='transparent'),
plot.background = element_rect(fill='transparent'),
panel.border = element_blank(),
axis.line = element_line(colour="black", size=1),
axis.title.x = element_text(colour='black',size=6),
axis.title.y = element_text(colour='black', size=6),
plot.caption = element_text('Figure 1. Residuals vs. fitted Values Model
1')
)
将按预期工作