Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

facet_wrap: How to add y axis to every individual graph when scales="free_x"?

Tags:

r

ggplot2

The following code

library(ggplot2)
library(reshape2)

m=melt(iris[,1:4])

ggplot(m, aes(value)) + 
  facet_wrap(~variable,ncol=2,scales="free_x") +
  geom_histogram()

produces 4 graphs with fixed y axis (which is what I want). However, by default, the y axis is only displayed on the left side of the faceted graph (i.e. on the side of 1st and 3rd graph).

What do I do to make the y axis show itself on all 4 graphs? Thanks!

EDIT: As suggested by @Roland, one could set scales="free" and use ylim(c(0,30)), but I would prefer not to have to set the limits everytime manually.

@Roland also suggested to use hist and ddply outside of ggplot to get the maximum count. Isn't there any ggplot2 based solution?

EDIT: There is a very elegant solution from @babptiste. However, when changing binwidth, it starts to behave oddly (at least for me). Check this example with default binwidth (range/30). The values on the y axis are between 0 and 30,000.

library(ggplot2)
library(reshape2)

m=melt(data=diamonds[,c("x","y","z")])

ggplot(m,aes(x=value)) + 
  facet_wrap(~variable,ncol=2,scales="free") +
  geom_histogram() +
  geom_blank(aes(y=max(..count..)), stat="bin")

enter image description here

And now this one.

ggplot(m,aes(x=value)) + 
  facet_wrap(~variable,scales="free") +
  geom_histogram(binwidth=0.5) +
  geom_blank(aes(y=max(..count..)), stat="bin")

enter image description here

The binwidth is now set to 0.5 so the highest frequency should change (decrease in fact, as in tighter bins there will be less observations). However, nothing happened with the y axis, it still covers the same amount of values, creating a huge empty space in each graph.

[The problem is solved... see @baptiste's edited answer.]

like image 680
jakub Avatar asked Jul 01 '13 09:07

jakub


2 Answers

Is this what you're after?

ggplot(m, aes(value)) + 
  facet_wrap(~variable,scales="free") +
  geom_histogram(binwidth=0.5) +
  geom_blank(aes(y=max(..count..)), stat="bin", binwidth=0.5)
like image 152
baptiste Avatar answered Oct 27 '22 01:10

baptiste


ggplot(m, aes(value)) + 
  facet_wrap(~variable,scales="free") +
  ylim(c(0,30)) +
  geom_histogram()
like image 27
Roland Avatar answered Oct 27 '22 01:10

Roland