我需要scatter plot
观察到的Vs使用Variable
的facet_wrap
功能预测每个ggplot
的数据。我可能很近但是还没到。我使用对上一个问题的答案中的一些建议,以gather
数据自动化plotting
过程。到目前为止,这是我的代码-我知道aes
的ggplot
错误,但是我故意使用它来阐明我的观点。我也想添加geom_smooth
以具有confidence interval
。
library(tidyverse)
DF1 = data.frame(A = runif(12, 1,10), B = runif(12,5,10), C = runif(12, 3,9), D = runif(12, 1,12))
DF2 = data.frame(A = runif(12, 4,13), B = runif(12,6,14), C = runif(12, 3,12), D = runif(12, 4,8))
DF1$df <- "Observed"
DF2$df <- "Predicted"
DF = rbind(DF1,DF2)
DF_long = gather(DF, key = "Variable", value = "Value", -df)
ggplot(DF_long, aes(x = Observed, y = Predicted))+
geom_point() + facet_wrap(Variable~.)+ geom_smooth()
我们将分别转换每个数据帧,然后将其绑定,因为x被观察,y被预测,然后是方面,请参见此示例:
library(ggplot2)
# reproducible data with seed
set.seed(1)
DF1 = data.frame(A = runif(12, 1,10), B = runif(12,5,10), C = runif(12, 3,9), D = runif(12, 1,12))
DF2 = data.frame(A = runif(12, 4,13), B = runif(12,6,14), C = runif(12, 3,12), D = runif(12, 4,8))
DF1_long <- gather(DF1, key = "group", "Observed")
DF2_long <- gather(DF2, key = "group", "Predicted")
plotDat <- cbind(DF1_long, DF2_long[, -1, drop = FALSE])
head(plotDat)
# group Observed Predicted
# 1 A 3.389578 10.590824
# 2 A 4.349115 10.234584
# 3 A 6.155680 8.298577
# 4 A 9.173870 11.750885
# 5 A 2.815137 7.942874
# 6 A 9.085507 6.203175
ggplot(plotDat, aes(x = Observed, y = Predicted))+
geom_point() +
facet_wrap(group~.) +
geom_smooth()
我们可以使用ggpubr将P和R值添加到绘图中,请参见answers in this post:
类似地,考虑使用基数R的merge
对整形后的数据帧使用reshape
(如果您是软件包作者,请避免使用任何tidyr
依赖项)。在lapply
+ Reduce
下,在全局环境中动态合并以绕过帮助器对象DF1_long和DF2_long:
数据
set.seed(10312019)
DF1 = data.frame(A = runif(12, 1,10), B = runif(12,5,10),
C = runif(12, 3,9), D = runif(12, 1,12))
DF2 = data.frame(A = runif(12, 4,13), B = runif(12,6,14),
C = runif(12, 3,12), D = runif(12, 4,8))
图
library(ggplot2) # ONLY IMPORTED PACKAGE
DF1$df <- "Observed"
DF2$df <- "Predicted"
DF = rbind(DF1, DF2)
DF_long <- Reduce(function(x,y) merge(x, y, by=c("Variable", "id")),
lapply(list(DF1, DF2), function(df)
reshape(df, varying=names(DF)[1:(length(names(DF))-1)],
times=names(DF)[1:(length(names(DF))-1)],
v.names=df$df[1], timevar="Variable", drop="df",
new.row.names=1:1E5, direction="long")
)
)
head(DF_long)
# Variable id Observed Predicted
# 1 A 1 6.437720 11.338586
# 2 A 10 4.690934 9.861456
# 3 A 11 6.116200 9.020343
# 4 A 12 6.499371 5.904779
# 5 A 2 6.779087 5.901970
# 6 A 3 6.499652 8.557102
ggplot(DF_long, aes(x = Observed, y = Predicted)) +
geom_point() + geom_smooth() + facet_wrap(Variable~.)