• Stars
    star
    374
  • Rank 110,215 (Top 3 %)
  • Language
    R
  • License
    Other
  • Created about 9 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ“Š Add marginal histograms to ggplot2, and more ggplot2 enhancements

ggExtra - Add marginal histograms to ggplot2, and more ggplot2 enhancements

CRAN version CI build

Copyright 2016 Dean Attali. Licensed under the MIT license.

ggExtra is a collection of functions and layers to enhance ggplot2. The flagship function is ggMarginal, which can be used to add marginal histograms/boxplots/density plots to ggplot2 scatterplots. You can view a live interactive demo to test it out!

Most other functions/layers are quite simple but are useful because they are fairly common ggplot2 operations that are a bit verbose.

This is an instructional document, but I also wrote a blog post about the reasoning behind and development of this package.

Note: it was brought to my attention that several years ago there was a different package called ggExtra, by Baptiste (the author of gridExtra). That old ggExtra package was deleted in 2011 (two years before I even knew what R is!), and this package has nothing to do with the old one.

Installation

ggExtra is available through both CRAN and GitHub.

To install the CRAN version:

install.packages("ggExtra")

To install the latest development version from GitHub:

install.packages("devtools")
devtools::install_github("daattali/ggExtra")

Marginal plots RStudio addin/gadget

ggExtra comes with an addin for ggMarginal(), which lets you interactively add marginal plots to a scatter plot. To use it, simply highlight the code for a ggplot2 plot in your script, and select ggplot2 Marginal Plots from the RStudio Addins menu. Alternatively, you can call the addin directly by calling ggMarginalGadget(plot) with a ggplot2 plot.

ggMarginal gadget screenshot

Usage

We’ll first load the package and ggplot2, and then see how all the functions work.

library("ggExtra")
library("ggplot2")

ggMarginal - Add marginal histograms/boxplots/density plots to ggplot2 scatterplots

ggMarginal() is an easy drop-in solution for adding marginal density plots/histograms/boxplots to a ggplot2 scatterplot. The easiest way to use it is by simply passing it a ggplot2 scatter plot, and ggMarginal() will add the marginal plots.

As a simple first example, let’s create a dataset with 500 points where the x values are normally distributed and the y values are uniformly distributed, and plot a simple ggplot2 scatterplot.

set.seed(30)
df1 <- data.frame(x = rnorm(500, 50, 10), y = runif(500, 0, 50))
p1 <- ggplot(df1, aes(x, y)) + geom_point() + theme_bw()
p1

And now to add marginal density plots:

ggMarginal(p1)

That was easy. Notice how the syntax does not follow the standard ggplot2 syntax - you don’t β€œadd” a ggMarginal layer with p1 + ggMarginal(), but rather ggMarginal takes the object as an argument and returns a different object. This means that you can use magrittr pipes, for example p1 %>% ggMarginal().

Let’s make the text a bit larger to make it easier to see.

ggMarginal(p1 + theme_bw(30) + ylab("Two\nlines"))

Notice how the marginal plots occupy the correct space; even when the main plot’s points are pushed to the right because of larger text or longer axis labels, the marginal plots automatically adjust.

If your scatterplot has a factor variable mapping to a colour (ie. points in the scatterplot are colour-coded according to a variable in the data, by using aes(colour = ...)), then you can use groupColour = TRUE and/or groupFill = TRUE to reflect these groupings in the marginal plots. The result is multiple marginal plots, one for each colour group of points. Here’s an example using the iris dataset.

piris <- ggplot(iris, aes(Sepal.Length, Sepal.Width, colour = Species)) +
  geom_point()
ggMarginal(piris, groupColour = TRUE, groupFill = TRUE)

You can also show histograms instead.

ggMarginal(p1, type = "histogram")

There are several more parameters, here is an example with a few more being used. Note that you can use any parameters that the geom_XXX() layers accept, such as col and fill, and they will be passed to these layers.

ggMarginal(p1, margins = "x", size = 2, type = "histogram",
           col = "blue", fill = "orange")

In the above example, size = 2 means that the main scatterplot should occupy twice as much height/width as the margin plots (default is 5). The col and fill parameters are simply passed to the ggplot layer for both margin plots.

If you want to specify some parameter for only one of the marginal plots, you can use the xparams or yparams parameters, like this:

ggMarginal(p1, type = "histogram", xparams = list(binwidth = 1, fill = "orange"))

Last but not least - you can also save the output from ggMarginal() and display it later. (This may sound trivial, but it was not an easy problem to solve - see this discussion).

p <- ggMarginal(p1)
p

You can also create marginal box plots and violin plots. For more information, see ?ggExtra::ggMarginal.

Using ggMarginal() in R Notebooks or Rmarkdown

If you try including a ggMarginal() plot inside an R Notebook or Rmarkdown code chunk, you’ll notice that the plot doesn’t get output. In order to get a ggMarginal() to show up in an these contexts, you need to save the ggMarginal plot as a variable in one code chunk, and explicitly print it using the grid package in another chunk, like this:

```{r}
library(ggplot2)
library(ggExtra)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
p <- ggMarginal(p)
```
```{r}
grid::grid.newpage()
grid::grid.draw(p)
```

removeGrid - Remove grid lines from ggplot2

This is just a convenience function to save a bit of typing and memorization. Minor grid lines are always removed, and the major x or y grid lines can be removed as well (default is to remove both).

removeGridX is a shortcut for removeGrid(x = TRUE, y = FALSE), and removeGridY is similarly a shortcut for… .

df2 <- data.frame(x = 1:50, y = 1:50)
p2 <- ggplot2::ggplot(df2, ggplot2::aes(x, y)) + ggplot2::geom_point()
p2 + removeGrid()

For more information, see ?ggExtra::removeGrid.

rotateTextX - Rotate x axis labels

Often times it is useful to rotate the x axis labels to be vertical if there are too many labels and they overlap. This function accomplishes that and ensures the labels are horizontally centered relative to the tick line.

df3 <- data.frame(x = paste("Letter", LETTERS, sep = "_"),
                  y = seq_along(LETTERS))
p3 <- ggplot2::ggplot(df3, ggplot2::aes(x, y)) + ggplot2::geom_point()
p3 + rotateTextX()

For more information, see ?ggExtra::rotateTextX.

plotCount - Plot count data with ggplot2

This is a convenience function to quickly plot a bar plot of count (frequency) data. The input must be either a frequency table (obtained with base::table) or a data.frame with 2 columns where the first column contains the values and the second column contains the counts.

An example using a table:

plotCount(table(infert$education))

An example using a data.frame:

df4 <- data.frame("vehicle" = c("bicycle", "car", "unicycle", "Boeing747"),
                  "NumWheels" = c(2, 4, 1, 16))
plotCount(df4) + removeGridX()

For more information, see ?ggExtra::plotCount.

More Repositories

1

beautiful-jekyll

✨ Build a beautiful and simple website in literally minutes. Demo at https://beautifuljekyll.com
HTML
4,938
star
2

advanced-shiny

🀹 Shiny tips & tricks for improving your apps and solving common problems
R
1,165
star
3

addinslist

πŸ“œ Discover and install useful RStudio addins
R
806
star
4

shinyjs

πŸ’‘ Easily improve the user experience of your Shiny apps in seconds
R
713
star
5

timevis

πŸ“… Create interactive timeline visualizations in R
R
632
star
6

shinycssloaders

βŒ› Add loading animations to a Shiny output while it's recalculating
CSS
393
star
7

shiny-server

My personal Shiny server
R
250
star
8

shinyalert

πŸ—―οΈ Easily create pretty popup messages (modals) in Shiny
R
225
star
9

oldschool-github-extension

Revert GitHub's UI back to its classic look (before the June 23, 2020 update that has a flat, rounded and more whitespaced design).
CSS
224
star
10

colourpicker

🎨 A colour picker tool for Shiny and for selecting colours in plots (in R)
JavaScript
205
star
11

shinyforms

πŸ“ Easily create questionnaire-type forms with Shiny
R
163
star
12

shinyscreenshot

πŸ“· Capture screenshots of entire pages or parts of pages in Shiny apps
R
67
star
13

shinydisconnect

πŸ”Œ Show a nice message when a Shiny app disconnects or errors
R
63
star
14

ddpcr

πŸ”¬ Analysis and visualization of Droplet Digital PCR data in R and on the web
R
58
star
15

daattali.github.io

Dean Attali's website - R/Shiny Consultant
HTML
54
star
16

shinybrowser

🌐 Find out information about a user's web browser in Shiny apps
R
41
star
17

lightsout

πŸ”¦ Lights Out game implemented in R
R
40
star
18

rsalad

A mix of useful R functions that are good for you
R
26
star
19

timevisBasic

Helper package to learn advanced 'htmlwidgets' tips
R
22
star
20

UBC-STAT545

My first 12 months with R, mostly through a UBC course and my own experiments
HTML
22
star
21

statsTerrorismProject

Final project for STAT545A - Terrorist activity data analysis
HTML
21
star
22

gslides-betternotes-extension

The slide previews in the Speaker Notes window of Google Slides are tiny and unreadable. This extension automatically resizes the slides when the window is resized, and allows the user to drag the sidebar to select a size.
JavaScript
21
star
23

github-diff-navigator-extension

Chrome/Firefox extension that allows you to easily navigate through the changes in a file that has been edited on GitHub.
JavaScript
19
star
24

shinytip

πŸ’¬ Simple flexible tooltips for Shiny apps
R
17
star
25

shinyfilebrowser

πŸ“ Simple file browser and list selector for Shiny apps
R
15
star
26

rasperry-pi-gaming-console-setup

How to set up raspberry pi as a portable oldies gaming console
13
star
27

cranalerts

Get email alerts when a CRAN package gets updated
R
11
star
28

shinymixpanel

πŸ” Track user interactions with Mixpanel in Shiny apps or R scripts
R
11
star
29

shiny-mini-workshop

Shiny Mini Workshop
R
9
star
30

single-page-amazon-return-labels-extension

Print Amazon return labels as a single page
JavaScript
8
star
31

settlers-catan-turn-analyzer

Settlers of Catan Turn Analyzer - a simple app to teach myself ReactJS
JavaScript
8
star
32

shinycodeviewer

πŸ“ View and edit a series of code chunks with syntax highlighting in Shiny
R
7
star
33

undomanager

πŸ”„ Generic undo/redo manager for R
R
7
star
34

shiny-colour-gradient-input

Colour gradient input for R-Shiny
R
6
star
35

smileyfy-my-facebook-extension

Chrome extension that adds infinite happiness to your Facebook browsing, plus a little bonus rickrolling :)
JavaScript
5
star
36

shiny-workshop-odsc2019

Shiny Workshop at ODSC 2019 (visualizing NBA 2018/19 player stats)
R
5
star
37

shinyHelpers

R
5
star
38

cashflow-calculation-extension

Cashflow Calculator extension for Zillow, Trulia, and Redfin (works in Chrome/Firefox/Edge)
JavaScript
4
star
39

modularize-addin

RStudio addin to help modularize Shiny app code
R
4
star
40

useR2017

Analysis of useR2017 attendance information
R
3
star
41

bingo

Generate Bingo cards with R.
R
3
star
42

Rlist

Easy way to navigate and explore list structures in R (abandoned project)
R
2
star
43

dash2

R
2
star
44

shiny-training-rstudioconf-2018

R
2
star
45

presentations

A place for me to keep my presentations/papers/etc organized
2
star
46

pftv-ad-bypass-extension

Project Free TV shows an interstitial ad page before allowing users to continue to the video - this extension bypasses that page
JavaScript
2
star
47

attalitech

AttaliTech Ltd
CSS
1
star
48

shinywc

R
1
star
49

shiny-conf-nyr-2022

R
1
star
50

stat540-2014-attali-dean

Lab work for UBC STAT540
R
1
star
51

htmldependencybug

JavaScript
1
star
52

genes-track-demo

HTML
1
star