This tutorial teaches you how to color words in a ggplot title to match the data in the plot itself. This approach has two main benefits:
- Improves interpretation: Readers can understand the chart more quickly.
- Reduces clutter: It can eliminate the need for a separate color legend.
We will use two R packages to accomplish this:
- Rcolorbrewer To identify the exact color codes used in the plot.
- use ggtext: To apply those colors to specific words in the title.
Grouped Barplot using Stock Price Data
Let us load the packages needed. We will use real stock market data to make the plots. We will use the R package tidyquant to get the stock market data.
library(ggtext) library(RColorBrewer) library(tidyverse) theme_set(theme_bw(16))
Let us make a grouped barplot showing the yearly returns of Google and S&P 500 index. First, we will download the daily stock price data for these two tickers using tidyquant’s tq_get() function for the time interval of interest.
stock_tickers = c("SPY","GOOG")
stock_df <- stock_tickers |>
tq_get(from = "2021-01-01", to=Sys.Date())
The downloaded stock price data looks like this.
stock_df %>% head() # A tibble: 6 × 8 symbol date open high low close volume adjusted <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 SPY 2021-01-04 375. 375. 365. 369. 110210800 351. 2 SPY 2021-01-05 368. 372. 368. 371. 66426200 353. 3 SPY 2021-01-06 370. 377. 369. 374. 107997700 355. 4 SPY 2021-01-07 376. 380. 376. 379. 68766800 360. 5 SPY 2021-01-08 381. 381. 377. 381. 71677200 362. 6 SPY 2021-01-11 378. 381. 378. 379. 51034700 360.
We will compute annual returns for these two stock tickers using tq_transmute() function in tidyquant.
yearly_return <- stock_df |>
group_by(symbol) |>
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "yearly") |>
ungroup()
yearly_return %>% head()
# A tibble: 6 × 3
symbol date yearly.returns
<chr> <date> <dbl>
1 SPY 2021-12-31 0.305
2 SPY 2022-12-30 -0.182
3 SPY 2023-12-29 0.262
4 SPY 2024-07-05 0.174
5 GOOG 2021-12-31 0.674
6 GOOG 2022-12-30 -0.387
How to add matching colors to select text in title
Let us make a grouped barplot with year on x-axis and returns on y-axis. We have colored the bars using scale_fill_brewer() with Dark2 palette.
yearly_return %>%
ggplot(aes(x=year(date), y=yearly.returns, fill=symbol))+
geom_col(position="dodge")+
scale_y_continuous(breaks=scales::breaks_pretty(6),
labels = scales::percent_format())+
scale_fill_brewer(palette="Dark2")+
labs(x=NULL,
title="Yearly Returns: S&P 500 vs Alphabet")
ggsave("How_to_add_matching_color_to_keywords_in_ggplot2_title.png")
Note the title text contains the two tickers name.
Getting color codes with brewer.pal()
To add matching colors to the names of the tickers in the title text, let first find what color codes we used to colr the bars. We can use RColoBrewer’s brewer.pal() function to get the color codes used in a palette.
my_colors <- brewer.pal(3,"Dark2") my_colors[1]
Add matching colors to select text in title with ggtext
Now that we have the color codes needed, we can use the R package ggtext to specify the colors to the select keywords in the title. We will use the same approach as selectively coloring the title text, but this time with matching colors. Check out the special html-style code in the title section of the code below.
In addition, we also need to add plot.title=element_markdown() to theme() and this renders the colors in the title text. Without adding ggtext’s element_markdown() we will not see the colors in the title instead we will see the actual html code.
yearly_return %>%
ggplot(aes(x=year(date), y=yearly.returns, fill=symbol))+
geom_col(position="dodge")+
scale_y_continuous(breaks=scales::breaks_pretty(6),
labels = scales::percent_format())+
scale_fill_brewer(palette="Dark2")+
labs(x=NULL,
title=paste0("Yearly Returns: <span style='color:",my_colors[1],"'>Alphabet </span> vs",
"<span style='color:",my_colors[2], "'> S&P 500</span>")) +
theme(plot.title = element_markdown(),
legend.position="none")
ggsave("add_matching_colors_to_title_text_ggplot2.png")
Explore the Complete ggplot2 Guide
35+ tutorials with code: scatterplots, boxplots, themes, annotations, facets, and more—tested and beginner-friendly.
Visit the ggplot2 Hub → No fluff—just code and visuals.