Re: [R] superposing barplots having different scales

From: Ben Bolker <bolker_at_ufl.edu>
Date: Wed, 28 May 2008 17:34:55 +0000 (UTC)

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

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Wed 28 May 2008 - 21:02:44 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 28 May 2008 - 21:30:57 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.