[R] Overlapping grid in plot

Duncan Murdoch murdoch at stats.uwo.ca
Sun Jan 16 11:00:36 CET 2005


On Sun, 16 Jan 2005 10:05:01 +0100, "Robin Gruna"
<robin_gruna at hotmail.com> wrote :

>Ok, here is some sample code to my problem
>
>> barplot(c(1,2,4,3,2), legend.text = "Legend")
>> grid()
>
>..the lines are crossing my barchart :-(...

The reason for this is the way R thinks of graphics, essentially as
ways to put ink on paper.  You draw the grid on top of the existing
plot.

Getting it to look the way you want is a little tricky:  you want to
draw the grid first so the bars appear on top, but R won't know how to
draw the grid until it has drawn the plot.  So the solution is to draw
the plot twice, e.g.

barplot(c(1,2,4,3,2), legend.text = "Legend")
grid(col='black', lty='solid')

oldpar <- par(bg='white') 
# this says to use a solid white background 
# instead of the default one, which is usually transparent.  The
# old colour is saved in oldpar

par(new=T) 
# this says to overwrite the plot

barplot(c(1,2,4,3,2), legend.text = "Legend")
par(oldpar) # restore the old colour	

Duncan Murdoch




More information about the R-help mailing list