【问题标题】:Align plot with barplot in R将绘图与 R 中的条形图对齐
【发布时间】:2016-12-23 18:29:03
【问题描述】:

我想显示两个具有相同 x 值的图。但情节并不一致。

如何对齐它们?


代码:

dat <- data.frame(d = LETTERS[1:5], c = c(39, 371, 389, 378, 790), r = c(39, 
    332, 18, -11, 412))

par(mfrow=c(2,1))

plot(dat$c, type = "s", ylim = c(0, max(dat$c)), xlab = "", ylab = "", axes = FALSE, col = "#4572a7", lwd = 2)
axis(1, at = c(1:length(dat$c)), labels = dat$d, lty = 0)
axis(2, lty = 0, las = 1)

barplot(dat$r, names.arg = dat$d, col = "#008000", border = NA, axes = FALSE)
axis(2, lty = 0, las = 1)
abline(h = 0, col = "#bbbbbb")

【问题讨论】:

    标签: r plot


    【解决方案1】:

    我们需要获取每个条形中心的 x 坐标,并将这些坐标用作第一个图的 x 值。我们还需要为每个绘图设置相同的xlim 值:

    # Get x coordinates of center of each bar
    pr = barplot(dat$r, names.arg = dat$d, col = "#008000", border = NA, axes = FALSE, 
                 plot=FALSE)
    
    par(mfrow=c(2,1))
    
    # Apply the x coordinates we just calculated to both graphs and give both 
    #  graphs the same xlim values
    plot(pr, dat$c, type = "s", ylim = c(0, max(dat$c)), xlab = "", ylab = "", axes = FALSE,
         col = "#4572a7", lwd = 2, xlim=range(pr) + c(-0.5,0.5))
    axis(1, at = pr, labels = dat$d, lty = 0)
    axis(2, lty = 0, las = 1)
    
    barplot(dat$r, names.arg = dat$d, col = "#008000", border = NA, axes = FALSE, 
            xlim=range(pr) + c(-0.5,0.5))
    axis(2, lty = 0, las = 1)
    

    【讨论】:

      猜你喜欢
      • 2015-08-27
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      相关资源
      最近更新 更多