Home > Net >  Adding circles around axis labels
Adding circles around axis labels

Time:01-06

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.

CodePudding user response:

There is probably a better way to do this, but you could convert the ggplot object to grob, then use grid.circle from grid to place the circles.

library(grid)
library(ggplotify)
library(ggplot2)

wordfrequencyplot_grob <- as.grob(wordfrequencyplot)

plot(wordfrequencyplot_grob)
grid::grid.circle(x=0.365, y=0.784, r=0.039, default.units="npc", name=NULL,
                  gp=gpar(fill = NA, col = "red", lwd = 2), draw=TRUE, vp=NULL)
grid::grid.circle(x=0.367, y=0.511, r=0.034, default.units="npc", name=NULL,
                  gp=gpar(fill = NA, col = "red", lwd = 2), draw=TRUE, vp=NULL)
grid::grid.circle(x=0.706, y=0.511, r=0.026, default.units="npc", name=NULL,
                  gp=gpar(fill = NA, col = "red", lwd = 2), draw=TRUE, vp=NULL)

Output

enter image description here

CodePudding user response:

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

  •  Tags:  
  • Related