开发者

Showing multiple axis labels using ggplot2 with facet_wrap in R

开发者 https://www.devze.com 2022-12-08 02:36 出处:网络
I\'ve got a nice facet_wrap density plot that I have c开发者_开发问答reated with ggplot2. I would like for each panel to have x and y axis labels instead of only having the y axis labels along the lef

I've got a nice facet_wrap density plot that I have c开发者_开发问答reated with ggplot2. I would like for each panel to have x and y axis labels instead of only having the y axis labels along the left side and the x labels along the bottom. What I have right now looks like this:

library(ggplot2)
myGroups <- sample(c("Mo", "Larry", "Curly"), 100, replace=T)
myValues <- rnorm(300)
df <- data.frame(myGroups, myValues)


p <- ggplot(df)  + 
  geom_density(aes(myValues), fill = alpha("#335785", .6)) + 
  facet_wrap(~ myGroups)
p

Which returns:

Showing multiple axis labels using ggplot2 with facet_wrap in R

(source: cerebralmastication.com)

It seems like this should be simple, but my Google Fu has been too poor to find an answer.


You can do this by including the scales="free" option in your facet_wrap call:

myGroups <- sample(c("Mo", "Larry", "Curly"), 100, replace=T)
myValues <- rnorm(300)
df <- data.frame(myGroups, myValues)


p <- ggplot(df)  + 
  geom_density(aes(myValues), fill = alpha("#335785", .6)) + 
  facet_wrap(~ myGroups, scales="free")
p

Showing multiple axis labels using ggplot2 with facet_wrap in R


Short answer: You can't do that. It might make sense with 3 graphs, but what if you had a big lattice of 32 graphs? That would look noisy and bad. GGplot's philosophy is about doing the right thing with a minimum of customization, which means, naturally, that you can't customize things as much as other packages.

Long answer: You could fake it by constructing three separate ggplot objects and combining them. But it's not a very general solution. Here's some code from Hadley's book that assumes you've created ggplot objects a, b, and c. It puts a in the top row, with b and c in the bottom row.

grid.newpage()
pushViewport(viewport(layout=grid.layout(2,2)))
vplayout<-function(x,y)
    viewport(layout.pos.row=x,layout.pos.col=y)
print(a,vp=vplayout(1,1:2))
print(b,vp=vplayout(2,1))
print(c,vp=vplayout(2,2))
0

精彩评论

暂无评论...
验证码 换一张
取 消