**使用可重复数据编辑**
我有一个数据框架,其中有50个实验处理的随时间增长的图表。我将它们绘制成一个多面的5x10绘图网格。考虑到我的实验性治疗,我也以一种有意义的方式命令它们。
我运行了一个回归函数来查找每个处理的增长率,并将斜率值保存在另一个数据框中。我已经绘制了数据,回归线和增长率的值,但我想根据回归斜率值为各个分面图的背景着色,但我无法弄清楚如何设置颜色来调用一个连续的变量,特别是一个来自不同行数的不同df(原始df有300行,我要调用的df有50个 - 每个处理一个)。
我的代码如下:
DF:
df <- data.frame(matrix(ncol = 3,nrow=300))
colnames(df) <- c("Trt", "Day", "Size")
df$Trt <- rep(1:50, each=6)
df$Day <- rep_len(1:6, length.out=300)
df$Size <- rep_len(c(3,5,8,9,12,12,3,7,10,16,17,20),length.out = 300)
回归函数和输出数据帧:
regression=function(df){
reg_fun<-lm(formula=df$Size~df$Day)
slope<-round(coef(reg_fun)[2],3)
intercept<-round(coef(reg_fun)[1],3)
R2<-round(as.numeric(summary(reg_fun)[8]),3)
R2.Adj<-round(as.numeric(summary(reg_fun)[9]),3)
c(slope,intercept,R2,R2.Adj)
}
library(plyr)
slopevalues<-ddply(df,"Trt",regression)
colnames(slopevalues)<-c ("Trt","slope","intercept","R2","R2.Adj")
情节:
ggplot(data=df, aes(x=Day, y=Size))+
geom_line() +
geom_point() +
xlab("Day") + ylab("Size (μm)")+
geom_smooth(method="lm",size=.5,se=FALSE)+
geom_text(data=slopevalues,
inherit.aes=FALSE,
aes(x =1, y = 16,hjust=0,
label=paste(slope)))+
facet_wrap(~ Trt, nrow=5)
我想要做的是根据渐变上的斜率值(斜率值$ slope)为各个图形的背景着色。我的真实数据不仅仅重复了2个值,所以我想根据该值在渐变颜色上执行此操作。
欢迎任何建议。
你可以使用带有无限坐标的geom_rect
来做到这一点:
ggplot(data=df, aes(x=Day, y=Size))+
## This is the only new bit
geom_rect(
aes(fill = slope, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf),
slopevalues,
inherit.aes = FALSE
) +
## New bit ends here
geom_line() +
geom_point() +
xlab("Day") + ylab("Size (μm)")+
geom_smooth(method="lm",size=.5,se=FALSE)+
geom_text(data=slopevalues,
inherit.aes=FALSE,
aes(x =1, y = 16,hjust=0,
label=paste(slope)))+
facet_wrap(~ Trt, nrow=5)