Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding shapes near to the text in ggplot

Tags:

r

ggplot2

I have below ggplot

library(ggplot2)
library(ggalt)
library(ggpp)
df <- data.frame(trt=LETTERS[1:5], l=c(20, 40, 10, 30, 50), r=c(70, 50, 30, 60, 80))

ggplot(df, aes(y=trt, x=l, xend=r)) +
  geom_text_npc(aes(npcx = 'center', npcy = 'bottom'), label = expression('No. of'~italic('AA')~'isolates with corresponding types'), parse = TRUE) +
  geom_dumbbell(aes(x = 'center', y = 'bottom'),
                size=3, color="#e3e2e1",
                colour_x = "#5b8124", colour_xend = "#bad744")

While this is generating some ggplot, however I want to add 2 shapes near to the text

  1. Add a square just to left of the text
  2. Add a rectangular bar to the bottom of the text.

For the second case, there is a possibility to just add underline to the text. However I found that is not optimal because, I can't change the width of the underline and there is no space between the text and the underline. I tried with geom_dumbbell() function, however it did not yield desired result.

My final ggplot should look like below

enter image description here

Is there anyway to achieve the desired ggplot like the attached snapshot?

Any pointer will be very helpful.

like image 575
Brian Smith Avatar asked Nov 17 '25 07:11

Brian Smith


1 Answers

You could use annotation_custom and place grobs that also use the "npc" units

out

library(ggplot2)
library(ggalt)
library(ggpp)
library(grid)

df <- data.frame(trt=LETTERS[1:5], l=c(20, 40, 10, 30, 50), r=c(70, 50, 30, 60, 80))

ggplot(df, aes(y = trt, x = l, xend = r)) +
  geom_dumbbell(size = 3, color = "#e3e2e1",
                colour_x = "#5b8124", colour_xend = "#bad744") +
  geom_text_npc(aes(npcx = 'center', npcy = 'bottom'), label = expression('No. of'~italic('AA')~'isolates with corresponding types'), parse = TRUE) +
  
  annotation_custom(
    grob = rectGrob(
      x = unit(0.5, "npc"), y = unit(0.04, "npc"),
      width = unit(0.4, "npc"), height = unit(0.011, "npc"),
      gp = gpar(fill = "gray60", col = NA)
    )
  ) +
  annotation_custom(
    grob = rectGrob(
      x = unit(0.325, "npc"), y = unit(0.058, "npc"),
      width = unit(0.025, "npc"), height = unit(0.025, "npc"),
      gp = gpar(fill = "darkred", col = "#e3e2e1")
    )
  ) 
like image 76
Tim G Avatar answered Nov 19 '25 23:11

Tim G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!