Tetley caffeine meter replication with ggplot2

[This article was first published on pacha.dev/blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Tetley tea boxes feature the following caffeine meter:

In R we can replicate this meter using ggplot2.

Move the information to a tibble:

library(dplyr)

caffeine_meter <- tibble(
  cup = c("Coffee", "Tea", "Green Tea", "Decaf Tea"),
  caffeine = c(99, 34, 34, 4)
)

caffeine_meter
# A tibble: 4 × 2
  cup       caffeine
  <chr>        <dbl>
1 Coffee          99
2 Tea             34
3 Green Tea       34
4 Decaf Tea        4

Now we can plot the caffeine meter using ggplot2:

library(ggplot2)

g <- ggplot(caffeine_meter) +
  geom_col(aes(x = cup, y = caffeine, fill = cup))

g

Then I add the colours that I extracted with GIMP:

pal <- c("#f444b3", "#3004c9", "#85d26a", "#3a5dff")

g + scale_fill_manual(values = pal)

The Decaf Tea category should be at the end of the plot, so I need to transform the “cup” column to a factor sorted decreasingly by the “caffeine” column:

library(forcats)

caffeine_meter <- caffeine_meter %>%
  mutate(cup = fct_reorder(cup, -caffeine))

g <- ggplot(caffeine_meter) +
  geom_col(aes(x = cup, y = caffeine, fill = cup)) +
  scale_fill_manual(values = pal)

g

Now I can change the background colour to a more blueish gray:

g +
  theme(panel.background = element_rect(fill = "#dcecfc"))

Now I need to add the title with a blue background, so putting all together:

caffeine_meter <- caffeine_meter %>%
  mutate(title = "Caffeine Meter\nIf brewed 3-5 minutes")

ggplot(caffeine_meter) +
  geom_col(aes(x = cup, y = caffeine, fill = cup)) +
  scale_fill_manual(values = pal) +
  facet_grid(. ~ title) +
  theme(
    strip.background = element_rect(fill = "#3304dc"),
    strip.text = element_text(size = 20, colour = "white", face = "bold"),
    panel.background = element_rect(fill = "#dcecfc"),
    legend.position = "none"
  )

To leave a comment for the author, please follow the link and comment on their blog: pacha.dev/blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)