'Add grid to background of multiple (bar)plots in one figure
So far I have only been able to obtain grids before the data, which is not what I need. Here is some example code.
par(mfrow=c(1,2))
barplot(x); box(); grid()
barplot(y); box(); grid()
All methods I have tried so far to shift the grid to the background does not work. Can somebody provide me with a simple way that accomplishes this?
Edit
par(mfrow=c(1,2))
barplot(mean_trend[,2],panel.first=grid(),names.arg = mean_trend[,1],col="skyblue",ylim = c(0.1,95),cex.names=0.6,ylab="Average precipitation in mm",cex.lab=0.85,lwd=1.5);box(lwd=1.5);grid()
barplot(freq_trend[,2],panel.first=grid(),names.arg = freq_trend[,1],col="skyblue",ylim = c(2,4500),cex.names=0.6,ylab="Average amount of floods",cex.lab=0.85,lwd=1.5);box(lwd=1.5);grid()
These are supposed to plot number of floods per year and mean severity of floods per year, for the period 2014-2021. So here column 1 is the year and column 2 is the amount, for both plots. Hope this helps
Kind regards.
Solution 1:[1]
I don't think the "panel.first" option is accepted by barplot. My suggestion for a base graphics solution is to use barplot twice with invisible bars the first time and without annotation the second time. The axes = FALSE option prevents the axis labels from being added again on the second call to barplot.
# simulated data for 8 years?
set.seed(456)
x <- runif(8, 1, 90)
y <- runif(8, 20, 4200)
# base graphics solution without all the decoration
par(mfrow = c(1, 2))
barplot(x, col = NA, border = NA, ylim = c(0, 95)); grid()
barplot(x, lwd = 1.5, add = TRUE, axes = FALSE); box(lwd = 1.5)
barplot(y, col = NA, border = NA, ylim = c(0, 4500)); grid()
barplot(y, lwd = 1.5, add = TRUE, axes = FALSE); box(lwd = 1.5)
box(lwd = 1.5)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David O |

