按组更改绘图的 x 轴值和背景颜色

Change x-axis values and background colour of a plot by group

我必须绘制以下随机生成的数据集的最后一列的值:

l <- seq(from=0.2, to=0.3, by=0.02)
output <- as.data.frame(matrix(NA,length(l)*4, 3))
colnames(output) <- c("G", "l", "Value")
output$G <- rep(2:5, each=length(l))
output$l <- rep(l, 4)
output$Value <- rnorm(nrow(output))
plot(output$Value, type="l")  

剧情现在是这样的

但如果可能的话,我希望在 x 轴上显示列“l”的值,它只是一个重复四次的向量。关于背景,我想知道是否可以根据 G 列的四个不同值将绘图分成四个箱(例如,通过交替背景颜色并添加解释 G 相应值的图例)。

您可以先绘制一个没有轴的空图,然后沿着 seq 的索引值构建它。我们需要 mtext() 来获得更小的 cex=。在 par()$usr 的帮助下,我们可以准确地定义边界,我们最终可以将其放入 rect().

plot(output$Value, type="l", axes=F)  
axis(1, seq(nrow(output)), labels=F)
mtext(output$l, 1, .5, at=seq(nrow(output)), cex=.75)
axis(2)
box()
p <- par()$usr
v <- c(0, with(output, seq(G)[diff(G) == 1]), p[2])
sapply(seq(v)[1:length(v) - 1], with(output, function(f) {
  rect(v[f], p[3], v[f + 1], p[4], col=f + 1)}))
lines(output$Value)  

但是,这是一种相当不寻常的方法,我建议为每个 G 使用一个面板,如下所示。这也消除了对轴进行修补的需要。

rg <- range(output$Value)

op <- par(mfrow=c(1, 4))
lapply(unique(output$G), function(x) {
  with(output[output$G == x, ], 
       plot(l, Value, type='l', main=paste0("G = ", x), ylim=rg))
  p <- par()$usr
  rect(p[1], p[3], p[2], p[4], col=x)
  with(output[output$G == x, ], lines(l, Value))
})
par(op)


数据:

output <- structure(list(G = c(2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 
3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L), l = c(0.2, 
0.22, 0.24, 0.26, 0.28, 0.3, 0.2, 0.22, 0.24, 0.26, 0.28, 0.3, 
0.2, 0.22, 0.24, 0.26, 0.28, 0.3, 0.2, 0.22, 0.24, 0.26, 0.28, 
0.3), Value = c(1.37095844714667, -0.564698171396089, 0.363128411337339, 
0.63286260496104, 0.404268323140999, -0.106124516091484, 1.51152199743894, 
-0.0946590384130976, 2.01842371387704, -0.062714099052421, 1.30486965422349, 
2.28664539270111, -1.38886070111234, -0.278788766817371, -0.133321336393658, 
0.635950398070074, -0.284252921416072, -2.65645542090478, -2.44046692857552, 
1.32011334573019, -0.306638594078475, -1.78130843398, -0.171917355759621, 
1.2146746991726)), row.names = c(NA, -24L), class = "data.frame")