Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

horizontal ggplot2::geom_violin without coord_flip

Tags:

r

ggplot2

I want to draw horizontal violin plots (because my labels are long). My design constraints are:

  • multiple facets (f1), multiple categories per facet (f2) (so I want to use aes(x=f2) and facet_wrap(~f1)
  • different scales per facet (so I want scales="free")
  • 4 different facets which I want to arrange via facet_wrap() (ruling out some faceting tricks)

Unfortunately scales="free" and coord_flip() are currently (and for the foreseeable future) incompatible.

The answers to this related question suggest (1) hacking a new horizontal geom; (2) exchanging x and y (which as pointed out there works only with symmetric geoms like scatterplots); (3) giving up and going with the conventional layout.

Ideas?

set.seed(101)
library("plyr")
dd <- expand.grid(f1=factor(1:2),
     f2=paste("inconveniently long label",1:2))
dd2 <- ddply(dd,c("f1","f2"),
             function(x)
                 data.frame(y=rnorm(100,
                         mean=10*(as.numeric(x$f2)), 
                         sd=10^(as.numeric(x$f1)))))
library("ggplot2")

My choices seem to be (1) with scale="free", inconvenient (horizontal) labels:

ggplot(dd2,aes(x=f2,y=y))+facet_wrap(~f1,scale="free")+geom_violin()

enter image description here

(2) with coord_flip(), inconvenient scales

ggplot(dd2,aes(x=f2,y=y))+facet_wrap(~f1)+geom_violin()+coord_flip()

enter image description here

Trying both (ggplot(dd2,aes(x=f2,y=y))+facet_wrap(~f1,scale="free")+geom_violin()+coord_flip()) gives

ggplot2 does not currently support free scales with a non-cartesian coord or coord_flip.

Other ideas:

  • There are explicitly horizontal versions of some geoms (geom_errorbarh); I could hack my own geom_violinh ...
  • There is some discussion of horizontal geoms in a pull request on ggplot2
  • This (rather old) example uses facets + geom_ribbon() to hack a violin plot, but it uses up faceting, making it incompatible with facet_wrap()

For what it's worth, this is what my real plot looks like (at the moment):

enter image description here

like image 644
Ben Bolker Avatar asked Jan 06 '16 21:01

Ben Bolker


1 Answers

This can now be done with the new (Jan 2016) ggstance package, which provides horizontal versions of a variety of geoms.

## if necessary
devtools::install_github("lionel-/ggstance")
## ... data generation stuff from above
require("ggplot2")
require("ggstance")
ggplot(dd2,aes(y=f2,x=y))+facet_wrap(~f1,scale="free")+
    geom_violinh()
like image 138
Ben Bolker Avatar answered Oct 02 '22 15:10

Ben Bolker