[R] Back-to-back graph with lattice package
David Winsemius
dwinsemius at comcast.net
Fri Oct 30 15:07:09 CET 2009
On Oct 30, 2009, at 9:11 AM, Erik Svensson wrote:
> Hi,
> I am an [R] and lattice beginner.
> I an doing an epidemiological study and want to present my data in a
> condensed and clear manner as possible.
>
> The example below is fake, but representative for the the data I
> want to show.
>
> I have a data frame with different categorical data and one column of
> numerical data:
>
> Country, Hair, Eyes, Sex, Age
> sweden, blond, blue, male, 25
> sweden, dark, brown, female, 30
> denmark, dark, blue, male, 22
> denmark, blond, blue, female 33
> norway, dark, blue, female, 21
> norway, blond, blue, male, 31
> finland, dark, blond, male, 43
> island, blond, blue, female, 40
> ...and so on for 300 rows...
>
> Country <- as.factor(rep(c("Sweden", "Denmark", "Norway", "Finland",
> "Iceland","Sweden", "Denmark", "Norway", "Finland","Sweden" ),50))
> Hair <- as.factor(rep(c("blond", "dark", "blond", "dark", "blond"),
> 100))
> Eyes <- as.factor(rep(c("blue", "blue", "blue", "brown"),125))
> Sex <- as.factor(rep(c("male", "female", "female", "male"),125))
> Age <- rep(c(1:20, 1:100, 76:80),4)
>
>
> Country has 5 levels, Age has many.
> Hair, Eyes, and Sex have two levels each
>
> I want to do one lattice graph with 5 columns of panels with these
> descriptive data.
> I would prefer to use the lattice barchart or the corresponding
> dotplot with lines (except for the Age panel)
>
> The Age panel and probably the Country panel I think I can solve
> myself:
> barchart(Country) # This only gives one panel, though...
> densityplot(~ Age|Country, layout=c(1,5), xlim=c(0,100),scales =
> list(y=list (relation="free")))
>
> But, for the dichotomous variables Hair, Eyes, and Sex columns I would
> like to have a bihistogram aka back-to-back aka age-sex-pyramid
> solution.
> I want all bars to be horizontal, the names of the countries to the
> left on the y-axis.
> I would also like to sort the country names according to a list of
> their names.
>
> For the back-to-back graph I have only managed to get two panels per
> column instead of one:
> barchart(table(Country, Hair),groups=FALSE)
My suggestion would be to look for a worked solution.
library(sos)
???pyramid
The two I found upon taking my own advice are pyramid in epicalc and
pyramid.plot in plotrix. Experimenting shows that the epicalc pyramid
solution is more flexible and requires less pre-processing of the data.
library(epicalc)
data(Oswego)
use(Oswego)
pyramid(age, sex)
# ... and on your data:
pyramid(Age, Hair) # ... seems to deliver the requested plot.
>
> How can I do all this? Is it possible at all?
library(fortunes)
fortune("Only how")
>
> Erik Svensson
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list