r - 为什么在 ggplot 中使用 theme() 会删除我预先指定的 labs() 命令?
问题描述
似乎是这样的,只要我在 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')
)
解决方案
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')
)
将按预期工作
推荐阅读
- laravel - 如何使用 laravel 中的一个函数在同一个文件中加载两个不同的视图
- python - 如何使用具有多个处理程序的 Python 日志记录模块将一条日志记录发送到文件,并将另一条日志记录发送到电子邮件
- python-3.x - 不确定tic_tac_toe换板
- java - 使用 Java 批量上传到 Box*
- javascript - 如何使用 JS 和 DOM 创建元素、设置属性、使用 innerHTML 和 appendChild
- c# - 如何从方法返回一些东西以打破 C# 中的循环?
- javascript - req.isAuthenticated() 重定向更改?
- azure - Azure“文本转语音”返回“无效的 CID 或语言”。这是什么意思?
- dictionary - 如何链接 LinkedList 节点以映射值
- opengl - GLFW_TRANSPARENT 和 GLFW_ALPHA_MASK 未定义