Search code examples
rggplot2scatter-plot

How do I add another set of datapoints to my scatterplot?


I have a toy dataset df:

df <- data.frame(
  title = c("Whispers in the Dark", "The Silent Shadows", "Echoes of the Forgotten", "The Vanishing Path", "Haunted Reflections"),
  downloads = c(84902, 78267, 81463, 102784, 112948),
  age_in_days = c(191, 184, 177, 170, 163),
  completion = c(59, 57, 43, 65, 71)
)

Using this data I have plotted age_in_days against downloads with this code:

library(ggplot2)
library(ggrepel)

ggplot(df, aes(x = age_in_days, y = downloads)) +
  geom_point() +
  geom_text_repel(aes(label = title), size = 3, box.padding = 0.35, point.padding = 0.3) +
  theme_minimal()
}

To give output:

plot (downloads against age in days)

I would like to add the completion data to the plot so that next to each episode title on the plot, you could also see the completion data (perhaps in brackets or a different colour). So the plot would be the same, but the labels would read: "Haunted Reflections (71)" or similar.

How can I visualise this data on my existing plot?


Solution

  • Using paste0 you can do:

    library(ggplot2)
    library(ggrepel)
    
    ggplot(df, aes(x = age_in_days, y = downloads)) +
      geom_point() +
      geom_text_repel(
        aes(label = paste0(title, " (", completion, ")")),
        size = 3, box.padding = 0.35, point.padding = 0.3
      ) +
      theme_minimal()