2016-12-23 8 views
2

Ich möchte zwei Plots mit den gleichen x-Werten übereinander anzeigen. Aber die Plots passen nicht zusammen.Align plot mit barplot in R

Wie kann ich sie ausrichten?


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

Antwort

1

Wir müssen die x-Koordinaten der Mitte jeder Bar bekommen und diese Koordinaten als die x-Werte des ersten Plot verwenden. Wir müssen auch die gleichen xlim Werte für jede Handlung setzen:

# 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