R ggplot2
ggplot2
In the earlier Graphics chapters, you used R's built-in functions, like plot() and barplot().
ggplot2 is a package for drawing graphs, and one of the most popular R packages. It is already installed in our editor, so you only need to load it with library(ggplot2).
In ggplot2, you build a graph in layers, with a + sign between each layer:
ggplot()sets the data, andaes()tells which columns go on the x-axis and the y-axis.- A
geom_function tells how to draw the data: as points, bars, lines, and so on. - More layers can add titles, colors and themes.
Scatter Plot
This scatter plot shows the weight (wt) and the miles per gallon (mpg) of the cars in the mtcars data set:
Example
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point()
Result:
ggplot() gets the data frame and the columns, and geom_point() draws one point for each car.
Note: Put the + sign at the end of a line, not at the start of the next line. Otherwise R thinks the graph ends on the first line.
Title, Labels and Themes
Use labs() to add a title and labels, and a theme like theme_minimal() to change the look of the whole graph:
Example
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
labs(title = "Weight and Miles per Gallon", x = "Weight", y = "Miles per gallon") +
theme_minimal()
Result:
Colors by Group
This is where ggplot2 really shines. Add color to aes(), and ggplot2 gives each group its own color, and adds a legend for you:
Example
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
labs(color = "Cylinders")
Result:
factor(cyl) tells ggplot2 that the number of cylinders is a category (see R Factors), and not a number on a scale.
Bar Chart
Use geom_col() to draw a bar chart. The fill argument sets the color of the bars:
Example
library(ggplot2)
fruits <- data.frame(
Fruit = c("Apple", "Banana", "Cherry"),
Amount = c(10, 25, 15)
)
ggplot(fruits, aes(x = Fruit, y = Amount)) +
geom_col(fill = "lightblue")
Result:
Histogram
Use geom_histogram() to draw a histogram. ggplot2 works with data frames, so we put the test scores in a data frame first. The binwidth argument sets how wide each bin is:
Example
library(ggplot2)
scores <- data.frame(
Score = c(55, 62, 68, 70, 71, 75, 78, 80, 82, 85, 88, 91, 95)
)
ggplot(scores, aes(x = Score)) +
geom_histogram(binwidth = 10, fill = "lightblue", color = "black")
Result:
Base R or ggplot2?
Both are good choices. The built-in functions are quick for simple graphs. ggplot2 needs a little more code, but makes it easy to color groups, add legends, and make graphs that look good.