One of the easiest ways to make a beautiful ggplot is by using a theme. ggplot2 comes with a variety of pre-existing themes. I’ll use the genre statistics summary table I created in yesterday’s post, and create the same chart with different themes.
reads2019 <- read_csv("~/Downloads/Blogging A to Z/SaraReads2019_allrated.csv",
col_names = TRUE)
genrestats <- reads2019 %>%
filter(Fiction == 1) %>%
group_by(Childrens, Fantasy, SciFi, Mystery) %>%
summarise(Books = n(),
WomenAuthors = sum(Gender),
AvgLength = mean(Pages),
AvgRating = mean(MyRating))
genrestats <- genrestats %>%
bind_cols(Genre = c("General Fiction",
"Children's Fantasy")) %>%
select(Genre, everything(), -Childrens, -Fantasy, -SciFi, -Mystery)
genre <- genrestats %>%
ggplot(aes(Genre, Books)) +
scale_y_continuous(breaks = seq(0,20,1))
Since I’ve created a new object for my figure, I can add a theme by typing genre + [theme]. Here’s a handful of the ggplot2 themes.
You can also get more themes with additional packages. My new favorite is ggthemes. I’ve been loving their Economist themes (particularly economist_white), which I’ve been using for most of the plots I create at work. Here are some of my favorites.
You can also customize different elements of the plot with theme(). For instance, theme(plot.title = element_text(hjust = 0.5)) centers your plot title. theme(legend.position = “none”) removes the legend. You could do both of these at once within the same theme() by separating them with commas. This is a great way to tweak tiny elements of your plot, or if you want to create your own custom theme.
## Warning: package 'ggthemes' was built under R version 3.6.3
theme(plot.background = element_rect(fill = "lightblue"))
These themes also have color schemes you can add to your plot. We’ll talk about that soon!