\documentclass[article,nojss]{jss}


<<package,include=FALSE,echo=FALSE>>=
options(keep.source = TRUE, width = 60)
packageInfo <- packageDescription("ggbeeswarm")
library(ggbeeswarm)
packageKeywords<-"visualization, display, one dimensional, grouped, groups, violin, scatter, points, quasirandom, beeswarm, van der Corput, beeswarm, ggplot, ggplot2"
@
%\VignetteIndexEntry{ggbeeswarm package usage examples}
%\VignetteDepends{}
%\VignetteKeywords{visualization, display, one dimensional, grouped, groups, violin, scatter, points, quasirandom, beeswarm, van der Corput, beeswarm, ggplot, ggplot2}
%\VignettePackage{ggbeeswarm}

\title{\pkg{\Sexpr{packageInfo$Package}} package usage example (version \Sexpr{packageInfo$Version})}
\author{\Sexpr{packageInfo$Author}}
\Plainauthor{\Sexpr{packageInfo$Author}}
\Address{ Github: \url{http://github.com/eclarke/ggbeeswarm}\\
  Cran: \url{https://cran.r-project.org/package=ggbeeswarm}
}

\Keywords{\Sexpr{packageKeywords}}

\Abstract{
  This is a collection of examples of usage for the \pkg{\Sexpr{packageInfo$Package}} package.
}

\begin{document}
\SweaveOpts{concordance=TRUE}
\SweaveOpts{engine=R,eps=FALSE}

\section{The basics}

This is the simplest example of using \code{geom_quasirandom} to generate violin scatter plots:
<<ggPlot, echo=TRUE, eval=FALSE>>=
  library(ggbeeswarm)
  set.seed(12345)
  n<-100
  dat<-rnorm(n*2)
  labs<-rep(c('a','b'),n)
  ggplot(mapping=aes(labs, dat)) + geom_quasirandom()
@

\begin{center}
<<showGgPlot, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<ggPlot>>
@
\end{center}


Normal \code{ggplot} options can be used:
<<ggOpts, echo=TRUE, eval=FALSE>>=
  ggplot(mapping=aes(labs, dat)) + geom_quasirandom(aes(color=labs))
@

\begin{center}
<<showGgOpts, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<ggOpts>>
@
\end{center}

Factors can be used to generate custom group orderings:
<<ggFactors, echo=TRUE, eval=FALSE>>=
  labs2<-factor(labs,levels=c('b','a'))
  ggplot(mapping=aes(labs2, dat)) + geom_quasirandom(aes(color=labs))
@
\begin{center}
<<showGgFactors, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<ggFactors>>
@
\end{center}

The axes can also be switched with a categorical y-axis:
<<yaxis, echo=TRUE, eval=FALSE>>=
  ggplot(mapping=aes(dat,labs)) + geom_quasirandom(aes(color=labs))
@
\begin{center}
<<showYaxis, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<yaxis>>
@
\end{center}

And dodging can be used to compare within groups:
<<dodge, echo=TRUE, eval=FALSE>>=
  labs2<-factor(rep(1:2,each=n))
  ggplot(mapping=aes(labs,dat,color=labs2)) + geom_quasirandom(dodge.width=.8)
@
\begin{center}
<<showDodge, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<dodge>>
@
\end{center}
Or on the y-axis:
<<dodgey, echo=TRUE, eval=FALSE>>=
  labs2<-factor(rep(1:2,each=n))
  ggplot(mapping=aes(dat,labs,color=labs2)) + geom_quasirandom(dodge.width=.8)
@
\begin{center}
<<showDodgey, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<dodgey>>
@
\end{center}

And with \code{geom_beeswarm}:
<<dodgeBee, echo=TRUE, eval=FALSE>>= labs2<-factor(rep(1:2,each=n))
  ggplot(mapping=aes(labs,dat,color=labs2)) +
    geom_beeswarm(dodge.width=.8,cex=2)
@
\begin{center}
<<showDodgeBee, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<dodgeBee>>
@
\end{center}
<<dodgeYBee, echo=TRUE, eval=FALSE>>=
  ggplot(mapping=aes(dat,labs,color=labs2)) +
    geom_beeswarm(dodge.width=.8,cex=2)
@
\begin{center}
<<showDodgeYBee, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<dodgeYBee>>
@
\end{center}

Both \code{geom_beeswarm} and \code{geom_quasirandom} also work with facets:
<<facetQuasi, echo=TRUE, eval=FALSE>>= labs2<-factor(rep(1:2,each=n))
  df<-data.frame(labs,dat,labs2)
  ggplot(df,aes(labs,dat,color=labs2)) +
    geom_quasirandom() +
    facet_grid(.~labs2)
@
\begin{center}
<<showFacetQuasi, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<facetQuasi>>
@
\end{center}
<<facetBee, echo=TRUE, eval=FALSE>>= labs2<-factor(rep(1:2,each=n))
  ggplot(df,aes(labs,dat,color=labs2)) +
    geom_beeswarm(cex=3) +
    facet_grid(.~labs2)
@
\begin{center}
<<showFacetBee, fig=TRUE, height=3.5, width=5, echo=FALSE>>=
<<facetBee>>
@
\end{center}






\section{Options}
There are several ways to plot grouped one-dimensional data combining points and density estimation including:
\begin{description}
	\item[pseudorandom] The kernel density is estimated then points are distributed uniform randomly within the density estimate for a given bin.  Selection of an appropriate number of bins does not greatly affect appearance but coincidental clumpiness is common.
	\item[alternating within bins] The kernel density is estimated then points are distributed within the density estimate for a given bin evenly spaced with extreme values alternating from right to left e.g. max, 3rd max, ..., 4th max, 2nd max. If maximums are placed on the outside then these plots often form consecutive ``smiley'' patterns. If minimums are placed on the outside then ``frowny'' patterns are generated. Selection of the number of bins can have large effects on appearance important.
	\item[tukey] An algorithm described by Tukey and Tukey in ``Strips displaying empirical distributions: I. textured dot strips'' using constrained permutations of offsets to distrbute the data.
	\item[quasirandom] The kernel density is estimated then points are distributed quasirandomly using the von der Corput sequence within the density estimate for a given bin.  Selection of an appropriate number of bins does not greatly affect appearance and position does not depend on plotting parameters.
	\item[beeswarm] The package \pkg{beeswarm} provides methods for generating a ``beeswarm'' plot where points are distibuted so that no points overlap. Kernel density is not calculated although the resulting plot does provide an approximate density estimate.  Selection of an appropriate number of bins affects appearance and plot and point sizes must be known in advance.
\end{description}

The first four options are included within \code{geom_quasirandom} using the \code{method=} argument and beeswarm plots are generated with \code{geom_beeswarm}:
<<methods, echo=TRUE, eval=FALSE, tidy=TRUE>>=
  library(gridExtra)
  dat <- list(
    'Normal'=rnorm(50),
    'Dense normal'= rnorm(500),
    'Bimodal'=c(rnorm(100), rnorm(100,5)),
    'Trimodal'=c(rnorm(100), rnorm(100,5),rnorm(100,-3))
  )
  labs<-rep(names(dat),sapply(dat,length))
  labs<-factor(labs,levels=unique(labs))
  dat<-unlist(dat)
  p1<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(alpha=.2) +
    ggtitle('quasirandom') + labs(x='') +
    theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
  p2<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(method='pseudorandom',alpha=.2) +
    ggtitle('pseudorandom') + labs(x='') +
    theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
  p3<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(method='smiley',alpha=.2) +
    ggtitle('smiley') + labs(x='') +
    theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
  p4<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(method='frowney',alpha=.2) +
    ggtitle('frowney') + labs(x='') +
    theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
  p5<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(method='tukey',alpha=.2) +
    ggtitle('tukey') + labs(x='') +
    theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
  p6<-ggplot(mapping=aes(labs, dat)) +
    geom_beeswarm(alpha=.2,size=.75) +
    ggtitle('geom_beeswarm') + labs(x='') +
    theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))
  grid.arrange(p1, p2, p3, p4, p5, p6, ncol=3)
@
\begin{center}
<<showMethods, fig=TRUE, height=8, width=6.5, echo=FALSE>>=
<<methods>>
@
\end{center}


\code{quasirandom} calls \code{vipor::offsetX} which calls \code{stats::density} to compute kernel density estimates. The tightness of the fit can be adjusted with the \code{bandwidth} option and the width of the offset with \code{width}. \code{nbins} to adjust the number of bins used in the kernel density is also provided but this can usually be left at its default when using quasirandom offsets but is useful for non-quasirandom methods:

<<distAdjust, echo=TRUE, eval=FALSE, tidy=TRUE>>=
  library(gridExtra)
  p1<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(bandwidth=2,alpha=.2) +
    ggtitle('bandwidth=2') + labs(x='')
  p2<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(bandwidth=.1,alpha=.2) +
    ggtitle('bandwidth=.1') + labs(x='')
  p3<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(width=.1,alpha=.2) +
    ggtitle('width=.1') + labs(x='')
  p4<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(nbins=100,alpha=.2) +
    ggtitle('nbins=100') + labs(x='')
  grid.arrange(p1, p2, p3, p4, ncol=1)
@
\begin{center}
<<showDistAdjust, fig=TRUE, height=8, width=6, echo=FALSE>>=
<<distAdjust>>
@
\end{center}


The \code{frowney} or \code{smiley} methods are sensitive to the number of bins so the argument \code{nbins} is more useful/necessary with them:
<<nbins, echo=TRUE, eval=FALSE, tidy=TRUE>>=
  p1<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(method='smiley',alpha=.2) +
    ggtitle('Default (n/5)') + labs(x='')
  p2<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(method='smiley',nbins=50,alpha=.2) +
    ggtitle('nbins=50') + labs(x='')
  p3<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(method='smiley',nbins=100,alpha=.2) +
    ggtitle('nbins=100') + labs(x='')
  p4<-ggplot(mapping=aes(labs, dat)) +
    geom_quasirandom(method='smiley',nbins=250,alpha=.2) +
    ggtitle('nbins=250') + labs(x='')
  grid.arrange(p1, p2, p3, p4, ncol=1)
@
\begin{center}
<<showNBins, fig=TRUE, height=8, width=6, echo=FALSE>>=
<<nbins>>
@
\end{center}

The \code{varwidth} argument scales the width of a group by the square root of the number of observations in that group (as in the function \code{boxplot}):
<<varwidth, echo=TRUE, eval=FALSE>>=
  dat <- list(
    '10 points'=rnorm(10),
    '50 points'=rnorm(50,2),
    '200 points'=c(rnorm(400), rnorm(100,5)),
    '5000 points'= rnorm(5000,1)
  )
  labs<-rep(names(dat),sapply(dat,length))
  labs<-factor(labs,levels=unique(labs))
  dat<-unlist(dat)
  ggplot(mapping=aes(labs, dat)) + geom_quasirandom(alpha=.3,varwidth=TRUE)
@
\begin{center}
<<showVarwidth, fig=TRUE, height=4, width=6, echo=FALSE>>=
<<varwidth>>
@
\end{center}

\section{Real data}
An example using the \code{beaver1} and \code{beaver2} data from the \pkg{datasets} package:
<<vpBeaver, echo=TRUE, eval=FALSE>>=
  beaver<-data.frame(
    'Temperature'=c(beaver1$temp,beaver2$temp),
    'Beaver'=rep(
      c('Beaver 1','Beaver 2'),
      c(nrow(beaver1),nrow(beaver2))
    )
  )
  ggplot(beaver,mapping=aes(Beaver, Temperature)) + geom_quasirandom()
@
\begin{center}
<<showBeaver, fig=TRUE, height=4, width=4, echo=FALSE>>=
<<vpBeaver>>
@
\end{center}

An example using the \code{integrations} data from the \pkg{vipor} package and the argument \code{dodge.width}:
<<vpGene, echo=TRUE, eval=FALSE>>=
  library(vipor)
  ints<-integrations[integrations$nearestGene>0,]
  ints$logGeneDist<-log(ints$nearestGene)
  ggplot(ints,mapping=aes(study, logGeneDist,color=latent)) +
  geom_quasirandom(dodge.width=.9,alpha=.4)
@
\begin{center}
<<showGene, fig=TRUE, height=4, width=6, echo=FALSE>>=
<<vpGene>>
@
\end{center}


\end{document}
