[R] Dotchart showing mean and median by group

Gabor Grothendieck ggrothendieck at gmail.com
Thu May 10 14:08:38 CEST 2012


On Thu, May 10, 2012 at 2:24 AM, maxbre <mbressan at arpa.veneto.it> wrote:
> hi all
>
> I have another question reated to the dotchart: is it possible by means of
> par() to set a logaritmic scale?
> If yes, how ? and if not, any alternative solution?
>

1. This is getting increasingly complicated as new requirements are
added but anyways here it is.  As before, for the first dotchart call
we substitute in our own dotchart (which is the same as R's dotchart
except its environment is reset to p so that it picks up anything in p
prior to similarly named functions elsewhere in R).  This time we also
add our own plot.window to p overriding log=.  The line marked ## is
optional and suppresses writing the axis annotations a second time.
As before, this code depends on the internals of dotchart so its not
ideal and you might wish to turn to lattice or ggplot 2 but it does
give the desired effect while sticking to classic graphics.

library(proto)

p <- proto(dotchart = dotchart,
	plot.window = function(..., log) graphics::plot.window(..., log = "x"))
with(p, dotchart(VADeaths, gdata = mean.values))

par(new = TRUE)

p[["axis"]] <- p[["mtext"]] <- list ##
with(p, dotchart(VADeaths, gdata = median.values, gpch = 20))

2. A variation is to use dotchart2 in Hmisc.   It has a version of
dotchart that directly supports adding to the plot.  Omit the
suppressWarnings call below if you don't mind a few spurious warnings.

library(Hmisc)

groups <- col(VADeaths, as.factor = TRUE)
labels <- rownames(VADeaths)[row(VADeaths)]

suppressWarnings({
  dotchart2(VADeaths, labels = labels, groups = groups,
    gdata = mean.values, log = "x")

  dotchart2(VADeaths, labels = labels, groups = groups,
    gdata = median.values, log = "x", pch = 1, add = TRUE)
})


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list