使用facet_wrap时stat_poly_eq标签手动定位失效问题求助
问题描述
现有如下结构的数据框df:
# 创建示例数据 RE <- c(0.95, 0.8, 0.7, 0.85, 0.5, 0.3, 1, 0.8, 0.2, 0.95, 0.4, 0) TimeSinceStart <- c(10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30) Name <- c("A","A","A","B","B","B", "A","A","A","B","B","B") VaporPressure <- c(1.1, 1.1, 1.1, 0.002, 0.002, 0.002, 1.1, 1.1, 1.1, 0.002, 0.002, 0.002) Aircleaner <- c("P1","P1","P1","P1","P1","P1","P2","P2","P2","P2","P2","P2") # 创建数据框 df <- data.frame(RE = RE, TimeSinceStart = TimeSinceStart, Name = Name, VaporPressure = VaporPressure, Aircleaner = Aircleaner, stringsAsFactors = FALSE) # 定义公式 my.formula <- y ~ x
其中Name与VaporPressure一一对应。需要绘制线性回归图,分析不同Aircleaner类别下log10(VaporPressure)与RE的相关性,使用stat_poly_eq并通过label.y手动设置公式标签位置时,设置失效——所有分面的标签都仅使用label.y的第一个值。尝试过label_repel,但仍会与数据点重叠(实际数据点数量更多)。
解决方案
在ggplot的aes()中添加group = Aircleaner即可解决标签位置失效的问题,有效代码如下:
ggplot(data = df, mapping = aes(log10(VaporPressure), RE, group = Aircleaner, color=TimeSinceStart))+ geom_point()+ geom_smooth(method = "lm", se=FALSE, formula = my.formula, size=.7, color="black") + stat_poly_eq(geom = "label_npc", formula = my.formula, parse = TRUE, aes(label = paste(..eq.label.., ..rr.label.., sep = "*plain(\",\")~~")), color="black", size = 3, label.y = c(0.3, 0.5))+ facet_wrap(Aircleaner~., ncol = 2)+ scale_color_continuous(name = "Operating time (h)")+ labs(x = bquote(log[10](p[v])), y = "RE (%)", title = NULL)+ theme(legend.position = "top")
内容的提问来源于stack exchange,提问作者Sara Bjerre Sørensen
相关产品推荐
相关产品推荐

