将情节与R

时间:2016-12-23 18:29:04

标签: r plot

我想显示两个相同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")

enter image description here

1 个答案:

答案 0 :(得分: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)

enter image description here