Search code examples
rggplot2graphaxisaxis-labels

Adding circles around axis labels


I would like to draw a red circle around the certain labels on the y axis. I have the following data and code to make a plot:

data <- structure(list(group = c("1", "1", "1", "2", "2", "2", 
"3", "3", "3"), word = c("headache", 
"computer", "window", "window", "plant", "coffee", "headache", "sky", 
"computer"), n = c(115L, 125L, 130L, 132L, 134L, 157L, 
195L, 209L, 215L), row = 1:9), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -9L))

#Define some colors to use throughout
my_colors <- c("#FFDBCE", "#8CAEAE", "#beb6d7")

wordfrequencyplot <- data %>%
  ggplot(aes(row, n, fill =as.factor(group))) +#as factor primetype to make it discrete 
    geom_col(show.legend = F) +
    labs(x = NULL, y = "Word Count") +
    facet_wrap(~group, scales = "free_y","fixed_x") +
    scale_x_continuous(  # This handles replacement of row 
      breaks = data$row, # notice need to reuse data frame
      labels = data$word) +
  scale_fill_manual(values = my_colors)+
    coord_flip()+
  theme_bw()

I want to draw circles around the words “coffee” and “plant” in group 2, and “sky” in group 3 on the y axis.


Solution

  • A very similar to solution to the one posted by @Andrew Gillreath-Brown would be to use the cowplot package to draw the circles on the original plot. However, you'll need to play with the x and y values of the circleGrob to get the desired output.

    library(cowplot)
    library(grid)
    
    # Draw circles as Grob
    g <- circleGrob(x = c(0.38, 0.38, 0.73),
                    y = c(0.51, 0.77, 0.51), 
                    r = 0.05,
                    gp = gpar(fill = "transparent",
                              col = "red",
                              lwd = 3))
    
    # Use ggdraw to add the circles over the original plot
    ggdraw(wordfrequencyplot) + 
      # Draw circles Grob
      draw_grob(g)
    

    enter image description here