user1322720
user1322720

Reputation:

Align plot with barplot in R

I want to display two plots with the same x-values above each other. But the plots don't align.

How can I align them?


Code:

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

Upvotes: 3

Views: 771

Answers (1)

eipi10
eipi10

Reputation: 93811

We need to get the x-coordinates of the center of each bar and use those coordinates as the x-values of the first plot. We also need to set the same xlim values for each plot:

# 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

Upvotes: 1

Related Questions