我已经为此制作了一个快速示例数据框。基本上我想创建一个线图,其平均值为一条线,并且该线周围的阴影代表值的范围。我意识到我可能必须找到行最小值/最大值,但我不确定如何为行执行此操作,也不知道如何绘制此行
TEST <- data.frame(a=c(1,5,7,2), b=c(3,8,2,5), c=c(6,10,2,1))
TEST$mean <- rowMeans(TEST)
感谢任何帮助 - 谢谢
答案 0 :(得分:6)
也可以轻松完成基础R,但这里采用ggplot
方法
添加Min
和Max
以及x
轴的某些索引
TEST <- transform(TEST, Min = pmin(a,b,c), Max = pmax(a,b,c), indx = seq_len(dim(TEST)[1]))
使用geom_ribbon
library(ggplot2)
ggplot(TEST) +
geom_line(aes(indx, mean), group = 1) +
geom_ribbon(aes(x = indx, ymax = Max, ymin = Min), alpha = 0.6, fill = "skyblue")
答案 1 :(得分:3)
只是添加另一个选项,这里只使用基础R:
是一个可能的解决方案TEST <- data.frame(a=c(1,5,7,2), b=c(3,8,2,5), c=c(6,10,2,1))
# compute mean, min and max of rows
means <- rowMeans(TEST)
maxs <- apply(TEST,1,max)
mins <- apply(TEST,1,min)
# create x-coordinates
xcoords <- 1:nrow(TEST)
# create an empty plot to make space for everything
plot(x=c(min(xcoords),max(xcoords)),y=c(min(mins),max(maxs)),
type="n", main="Average",xlab="X",ylab="Y")
# add min-max ranges (color is DodgerBlue with 80/255 of opacity,
# for rgb values of colors see http://en.wikipedia.org/wiki/Web_colors)
rangecolor <- rgb(30,144,255,alpha=80,maxColorValue=255)
polygon(x=c(xcoords,rev(xcoords)),y=c(maxs,rev(means)),col=rangecolor,border=NA)
polygon(x=c(xcoords,rev(xcoords)),y=c(mins,rev(means)),col=rangecolor,border=NA)
# add average line (black)
meancolor <- "black"
lines(x=xcoords,y=means,col=meancolor)
结果:
为了将来重用,您还可以将其包装成一个有用的功能:
plotLineWithRange <- function(x, yVal, yMin, yMax,
lineColor="Black", rangeColor="LightBlue",
main="", xlab="X", ylab="Y"){
if(missing(x)){
x <- 1:length(yVal)
}
stopifnot(length(yVal) == length(yMin) && length(yVal) == length(yMax))
plot(x=c(min(x),max(x)),y=c(min(yMin),max(yMax)),type="n", main=main,xlab=xlab,ylab=ylab)
polygon(x=c(x,rev(x)),y=c(yMax,rev(yVal)),col=rangeColor,border=NA)
polygon(x=c(x,rev(x)),y=c(yMin,rev(yVal)),col=rangeColor,border=NA)
lines(x=x,y=yVal,col=lineColor)
}
# usage example:
plotLineWithRange(yVal=means,yMin=mins,yMax=maxs,main="Average")