Skip to content

R Visualization: Basics of ggplot2

Abish Pius edited this page Mar 3, 2020 · 1 revision

ggplot2 Introduction

  • ggplot2 is part of the tidyverse suite of packages, which you can load with library(tidyverse).
  • Note that you can also load ggplot2 alone using the command library(ggplot2), instead of loading the entire tidyverse.
  • ggplot2 uses a grammar of graphics to break plots into building blocks that have intuitive syntax, making it easy to create relatively complex and aesthetically pleasing plots with relatively simple and readable code.
  • ggplot2 is designed to work exclusively with tidy data (rows are observations and columns are variables).

Graph Components

  • Plots in ggplot2 consist of 3 main components:
    • Data: The dataset being summarized
    • Geometry: The type of plot (scatterplot, boxplot, barplot, histogram, qqplot, smooth density, etc.)
    • Aesthetic mapping: Variables mapped to visual cues, such as x-axis and y-axis values and color
  • There are additional components:
    • Scale
    • Labels, Title, Legend
    • Theme/Style

Creating a New Plot

  • You can associate a dataset x with a ggplot object with any of the 3 commands:
    • ggplot(data = x)
    • ggplot(x)
    • x %>% ggplot()
  • You can assign a ggplot object to a variable. If the object is not assigned to a variable, it will automatically be displayed.
  • You can display a ggplot object assigned to a variable by printing that variable.

Code: Creating a New Plot

library(tidyverse)
library(dslabs)
data(murders)

ggplot(data = murders)

murders %>% ggplot()

p <- ggplot(data = murders)
class(p)
print(p)    # this is equivalent to simply typing p
p

Clone this wiki locally