[R] superposing barplots having different scales
Ben Bolker
bolker at ufl.edu
Wed May 28 19:34:55 CEST 2008
Bill Shipley <bill.shipley <at> usherbrooke.ca> writes:
>
> Hello. I know how to make a bar plot in which a numeric y variable is
> plotted against some grouping variable X (say, groups A, B, C) when this
> grouping variable is subdivided into each of two subgroups; so the bars
> would be: (group A subgroup 1) beside (group A subgroup 2), then (group B
> subgroup 1) beside (group B subgroup 2), and so on. This is done using the
> beside=TRUE argument in the barplot() function. However, I want to make a
> slightly different type of barplot in which the numerical values of the
> subgroups (subgroups 1 and 2) are measured in very different scales. I want
> to use different scales to define the numerical y values for each subgroup.
> This graph would have one scale on the left-hand y-axis and a second scale
> on the right-hand y-axis.
>
> I cannot simply superimpose two bar plots because I have to make sure that
> the subgroup bars are beside each other.
>
> Bill Shipley
>
Bill,
I think that all the arguments for why NOT to create
scatterplots with two different y-axes apply here --
(see recent R-help threads and the wiki) --
consider a scatterplot, or some other way of presenting
the data, instead?
Nevertheless -- the easiest way to do this (I think)
is to scale subgroup 2, then plot the right-hand axis
with labels appropriate for the unscaled data, as follows:
dat = matrix(c(1,2,3,1000,2000,3000),ncol=2,
dimnames=list(c("A","B","C"),c("meas1","meas2")))
## scale groups to have the same max. value
scale <- max(dat[,"meas2"]/dat[,"meas1"])
## apply scale to second subgroup
dat2 = dat
dat2[,"meas2"] <- dat2[,"meas2"]/scale
barplot(t(dat2),beside=TRUE)
ticks = pretty(dat[,"meas2"]) ## on original data scale
axis(side=4,at=ticks/scale,label=ticks)
I haven't bothered with any prettiness like
setting aside margins for the right-hand axis, etc etc
More information about the R-help
mailing list