Visualizing Data in R with ggplot2:
Patchwork and Plotly Package

Somsak Chanaim

International College of Digital Innovation, CMU

October 30, 2024

What is the patchwork package?

The patchwork package is the one extension of ggplot2 package.

The goal of patchwork package is to make it ridiculously simple to combine separate ggplots into the same graphic.

How to in install

How to use their package

The ggplot Graph Example

From mtcars data set

Adding plots to the patchwork

We can use \(+\) to add plots together in the same row (up to three plots).

Stacking and packing

We can use \(/\) to add plots together in the same column.

Mixed plot with multi rows and column

We can mix the plots with multiple rows and columns.

or

For up to 4 plots or more

We can control by using this command

Nesting the left-hand side

As plots will always be added to the patchwork on the left-hand side, it is not possible to nest the left-hand side beside the right-hand side with the standard operators shown above.

Nesting the right-hand side

As plots will always be added to the patchwork on the right-hand side, it is not possible to nest the left-hand side beside the right-hand side with the standard operators shown above.

Modifying theme

Often, especially when it comes to theming, you want to modify everything at once. patchwork provides two additional operators that facilitates this. \& will add the element to all subplots in the patchwork, and * will add the element to all the subplots in the current nesting level.

Adding Annotation and Style

Titles, subtitles and captions

One of the most needed things is to add descriptive text to your plot ensemble. To achieve this, you simply add it to your patchwork using plot_annotation()

Plotly package

What is Plotly?

Plotly is an open-source data visualization library for Python and R written in JavaScript, making graphs inherently interactive.

We can be modified tremendously and are easily exported as images, HTML, etc. for seamless integration into a number of applications.

How to use plotly

step 1: Created a ggplot object.

step 2: put ggplot object in ggplotly() function

View multiple plots in a single view with plotly by the subplot() function

Warning

  • plotly is not working with the ggplot object from patchwork.

  • plotly is not working for pdf output.