Add color to your ggplot2 text in R

The ggplot2 package is powerful and almost endlessly customizable, but sometimes small tweaks can be a challenge. The ggtext package aims to simplify styling text on your visualizations. In this tutorial, I’ll walk through one text-styling task I saw demo’d at RStudio Conference last month: adding color.

If you’d like to follow along, I suggest installing the development version of ggplot2 from GitHub. In general, some things shown at the conference weren’t on CRAN yet. And ggtext definitely does not work with some older versions of ggplot.

You have to install ggtext from GitHub, since at the time I wrote this, the package wasn’t yet on CRAN. I use remotes::install_github() to install R packages from GitHub, although several other options, such as devtools::install_github(), work as well. Note that in the code below I include the argument build_vignettes = TRUE so I have local versions of package vignettes. After that, I load ggplot2, ggtext, and dplyr.

remotes::install_github("tidyverse/ggplot2", build_vignettes = TRUE)
remotes::install_github("wilkelab/ggtext", build_vignettes = TRUE)

For demo data, I’ll use data comparing tweets about R (with the #rstats hashtag) with tweets about Python (#python). After downloading recent tweets, I did some filtering, took a random sample of 1,000 of each, and then calculated how many in each group had at least five likes, had at least five retweets, included a URL, and included media like a photo or video.

You can re-create the data set with the code block below. Or you could use any data set that makes sense as a grouped bar chart and modify my subsequent graph code accordingly.

Copyright © 2020 IDG Communications, Inc.

Source link