R Ggplot2

The ggplot2 package is a graphing library.


Installation

ggplot2 is commonly used through Tidyverse.


Usage

ggplot() returns a ggplot object. Components are inserted with the addition (+) operator.

library(tidyverse)
ggplot(data = DATA, mapping = aes(MAPPINGS)) +  GEOM_FUNC()


Theming

Themes are used to customize the appearance of a graph. They are applied to a ggplot object with the addition (+) operator.

library(tidyverse)
ggplot(data = DATA, mapping = aes(MAPPINGS)) +  GEOM_FUNC() + THEME_OBJ

Theme Objects

A set of default themes are provided by the ggplot2 package. theya re accessible from these functions:

Otherwise, construct a theme object using theme().

library(tidyverse)
mytheme <- theme(OPTIONS)
ggplot(data = DATA, mapping = aes(MAPPINGS)) +  GEOM_FUNC() + mytheme

A common strategy is to use one of the above default themes as a starting point and then to apply customizations.

library(tidyverse)
ggplot(data = DATA, mapping = aes(MAPPINGS)) +  GEOM_FUNC() + theme_minimal() + theme(OPTIONS)

Options

To set the font for a graph's text:

theme(text = element_text(family = "DejaVu"))

To enlarge the title:

theme(plot.title = element_text(size = 20))

Note that targetting title instead of plot.title would affect the size of all title-like objects (e.g. axes labels, legend title, and so on).

To rotate the x-axis labels 90 degrees:

theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5))

To color the y-axis labels:

theme(axis.text.y = element_text(colour = "grey20"))

To italicize the group titles in a faceted plot:

theme(strip.text = element_text(face = "italic"))


See also

ggplot2 theme reference

ggplot2 default themes reference


CategoryRicottone

R/Ggplot2 (last edited 2023-06-15 17:31:56 by DominicRicottone)