我正在尝试在几个数据集的散点图中添加R2的值,并使用facet_grid。所以,我想在每个图中添加几个文本(R2的值,每个数据集各一个)。我一直在寻找类似的例子,但我无法找到正确的方法,因为我不知道如何设置文本的x和y位置。
这是我原始数据的一个非常简短的样本:
dput(test)
structure(list(code = c("AT0ENK1", "AT0ENK1", "AT0ENK1", "AT0ENK1",
"AT0ENK1", "AT0ENK1", "AT0ENK1", "AT0ENK1", "AT0ILL1", "AT0ILL1",
"AT0ILL1", "AT0ILL1", "AT0ILL1", "AT0ILL1", "AT0ILL1", "AT0ILL1"
), model = structure(c(2L, 2L, 2L, 2L, 6L, 6L, 6L, 6L, 2L, 2L,
2L, 2L, 6L, 6L, 6L, 6L), .Label = c("Obs", "EMEP", "LOTO", "MATCH",
"MINNI", "WRFF", "WRFM"), class = "factor"), O3 = c(118.037246704102,
105.963432312012, 102.795967102051, 107.245376586914,
101.879364013672,
124.914794921875, 129.386352539062, 115.475601196289,
96.2464294433594,
113.553771972656, 108.113143920898, 95.6128845214844,
104.497161865234,
111.243560791016, 121.166435241699, 118.756866455078), O3obs =
c(144.424,
151.726, 151.866, 139.439, 144.424, 151.726, 151.866, 139.439,
164.202, 171.715, 158.06, 137.473, 164.202, 171.715, 158.06,
137.473), r2 = c(0.485277006453918, 0.485277006453918,
0.485277006453918,
0.485277006453918, 0.277829662775301, 0.277829662775301,
0.277829662775301,
0.277829662775301, 0.0429530296631768, 0.0429530296631768,
0.0429530296631768,
0.0429530296631768, 0.0332266668960316, 0.0332266668960316,
0.0332266668960316,
0.0332266668960316)), .Names = c("code", "model", "O3", "O3obs",
"r2"), class = "data.frame", row.names = c(1L, 2L, 3L, 4L, 125L,
126L, 127L, 128L, 187L, 188L, 189L, 190L, 311L, 312L, 313L, 314L
))
我尝试过:
ggplot( test, aes(O3obs,O3, group= model)) +
geom_point(aes(color=model),size=1)+xlim(0,200) + ylim (0,200) +
geom_abline(intercept = 0, slope = 1) + facet_wrap(~code) +
geom_text(data=test, aes(color = model, label = paste("R2: ", round(r2,2), sep="")), x=180, y=Inf, show.legend = F)
但R2的值重叠。
有什么建议吗?如何为每个图中的每个数据添加R2的值?
答案 0 :(得分:0)
当您在geom_text中指定x和y时,您将为所有文本指定相同的坐标,以便它们重叠是有意义的。我通常通过创建一个具有每个组的x和y坐标的数据框来解决这个问题。对于您的数据,这可能如下所示:
require(dplyr)
require(ggplot2)
new_data = test %>% group_by(code, model) %>% summarise(r2 = max(r2))
new_data$xposition = 40
new_data$yposition = c(200,170,200,170)
ggplot( test, aes(O3obs,O3, group= model))+
geom_point(aes(color=model),size=1)+xlim(0,200) + ylim (0,200) +
geom_abline(intercept = 0, slope = 1) + facet_wrap(~code) +
geom_text(data=new_data,aes(x = xposition, y = yposition, color=model, label = paste("R2: ",
round(r2,2),sep="")),show.legend = F)