【问题标题】:Change x-axis values and background colour of a plot by group按组更改绘图的 x 轴值和背景颜色
【发布时间】:2021-08-11 07:32:22
【问题描述】:

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

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 的相应值的图例)。

【问题讨论】:

    标签: r plot random graph colors


    【解决方案1】:

    您可以先绘制一个没有轴的空图,然后沿着索引值的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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多