[R] Smoothed lines over barplots

Ott Toomet siim at obs.ee
Wed Feb 20 10:36:17 CET 2002


Hi,

On Tue, 19 Feb 2002, Andrew Perrin wrote:

.Greetings.
.
I'd like to generate a graph that displays two distributions as
.side-by-side bar graphs, then plots a smoothed line of the distribution on
.top. The idea is to be able to visually compare the distributions.
.
.I've done the following, but the axes don't line up. Any suggestions?
.
.barplot(table(hcd.df$datecat, hcd.df$auth.sum), beside=TRUE,
.  legend.text=c('Pre-9/11','Post-9/11'),main='Authoritarian Sum',
.  sub='Chi-Square: 33.88; p< .01',col=c('yellow','red'))
.par(new=TRUE)
.plot(table(hcd.df$auth.sum[hcd.df$datecat==1]), type='l',xlim=c(-8,7),
.  ylim=c(0,59),col='yellow')
.par(new=TRUE)
.plot(table(hcd.df$auth.sum[hcd.df$datecat==2]), type='l',
.  col='red',xlim=c(-8,7), ylim=c(0,59))
.

The minor problem is that you use par(new=TRUE) on plot() instead of
lines().  lines() automatically keeps the old figure (including definition
of axes).

The major problem is that when ploting as you do: plot(table(..),...) the
plot is assuming the x-coordinates are 1,2,3,.... This is not what is done
by barplot.  Barplot() calculates its own x-values which do not correspond
to the labels.  Luckily you can get its values quite easily.  Simply write

bp <- barplot(..., beside=T)

and bp is a matrix where you have the means of x-coordinates of the bars.
So you can do somthing like

datecat <- rbinom(100,1,0.5)
auth.sum <- rbinom(100,10,0.5)
bp <- barplot(table(datecat, auth.sum), beside=TRUE,col=c('yellow','red'))
mean.bp <- apply(bp,2,mean)
lines(mean.bp,table(auth.sum,datecat)[,1], col="yellow")
lines(mean.bp,table(auth.sum,datecat)[,2], col="red")

Note that it is safer to use table(...)[,1] instead of table(...[..==1]) --
you get value 0 instead with in the first way but one datapoint less with
the second way.

In fact it was no smoothing here.

Cheers,

Ott Toomet

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list