[R] Overlapping grid in plot
Marc Schwartz
MSchwartz at MedAnalytics.com
Sun Jan 16 17:22:21 CET 2005
On Sun, 2005-01-16 at 05:00 -0500, Duncan Murdoch wrote:
> 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
You can also look at the barplot2() function, which is in the 'gregmisc'
bundle on CRAN and take note of the 'plot.grid' argument, which will
enable a grid to be drawn behind the bars. As an example:
[after installing gregmisc]
library(gplots)
barplot2(c(1, 2, 4, 3, 2), legend.text = "Legend",
plot.grid = TRUE, grid.lty = "solid")
This will result in horizontal lines behind the bars at the same points
as the y axis default tick marks.
HTH,
Marc Schwartz
More information about the R-help
mailing list