[R] ggplot2 / histogram / y-axis

hadley wickham h.wickham at gmail.com
Thu Jul 12 21:43:11 CEST 2007


On 7/12/07, Pete Kazmier <pete-expires-20070910 at kazmier.com> wrote:
> Is there a way in ggplot to make a histogram with the left-hand y-axis
> label as frequency, and a right-hand y-axis label as percentage?

Not currently.  I did a quick exploration to see if it was feasible to
draw another axis on with grid, but it doesn't look like it's
possible:

p <- qplot(rating, data=movies, geom="histogram")

# Map aesthetics to data
data <- p$layers[[1]]$make_aesthetics(p)
# Calculate statistic "by hand" (we'll need this to get the scales right)
binned <- StatBin$calculate(data=data, p$scales)

n <- nrow(movies)

# Manually recreate the y scale
sp <- scale_y_continuous()
sp$train(binned$count)

# rescale the labels
labels <- formatC(sp$breaks() / n, digits=2)

# Have to do without labels because of bug in grid
print(p, pretty=FALSE)
downViewport("panel_1_1")
grid.draw(ggaxis(sp$breaks(), as.list(labels), "right", sp$frange()))

# Why don't labels line up? - I'm not sure
# How could you make space for the extra axis? - Not sure either
# How would this worked for a facetted graphic - not well


Also how were you expecting the axes/gridlines to line up?  Would both
axes be labelled "nicely" (with whole numbers) and the secondary axis
wouldn't have gridlines; or would the second axis match the lines of
the primary, even though the number wouldn't be so attractive?

Hadley



More information about the R-help mailing list