0

If I have a bar graph like below,

x<- c("a","b","c","d","e")
y<- c(5,7,12,19,25)
dataA<- data.frame (x,y)

ggplot(data=dataA, aes(x=x, y=y)) + 
  geom_bar(stat="identity",position="dodge", width = 0.7) + 
  geom_hline(yintercept=0, linetype="solid", color = "Black", size=1) +
  scale_y_continuous(breaks = seq(-2,30,3),limits = c(-2,30)) +
  labs(fill= NULL, x="Cultivar", y="Yield") +
  theme(axis.title = element_text (face = "plain", size = 18, color = "black"),
        axis.text.x = element_text(size= 15),
        axis.text.y = element_text(size= 15),
        axis.line = element_line(size = 0.5, colour = "black"),
        legend.position = 'none') +
  windows(width=7.5, height=5)

enter image description here

I'd like to draw a box in the graph of d and e to emphasize. Could you tell me how to draw a box or circle (or other shapes) inside graph?

Thanks,

Jin.w.Kim
  • 599
  • 1
  • 4
  • 15

1 Answers1

3

You should achieve what you are looking for in this specific case by setting the type of x column to factor and adding the rectangle layer to ggplot with geom_rect(). Linetype = 8 inside the geom_rect function gives the dashed line as in the figure you provided. This approach is taken in the code below. Another function that would allow adding the rectangle is annotate(), which also supports other kind of annotations. About circles specifically, this exists already: Draw a circle with ggplot2.

x <- c("a","b","c","d","e")
y <- c(5,7,12,19,25)
dataA <- data.frame(x,y)
dataA$x <- as.factor(dataA$x)

ggplot(data=dataA, aes(x=x, y=y)) + 
  geom_bar(stat="identity",position="dodge", width = 0.7) + 
  geom_hline(yintercept=0, linetype="solid", color = "Black", size=1) +
  scale_y_continuous(breaks = seq(-2,30,3), limits = c(-2,30)) +
  labs(fill = NULL, x = "Cultivar", y = "Yield") +
  theme(axis.title = element_text (face = "plain", size = 18, color = "black"),
        axis.text.x = element_text(size= 15),
        axis.text.y = element_text(size= 15),
        axis.line = element_line(size = 0.5, colour = "black"),
        legend.position = 'none') +
  windows(width=7.5, height=5) +
  geom_rect(xmin = as.numeric(dataA$x[[4]]) - 0.5,
            xmax = as.numeric(dataA$x[[5]]) + 0.5,
            ymin = -1, ymax = 28,
            fill = NA, color = "red",
            linetype = 8)
Undis
  • 46
  • 3
  • It works perfectly!!! I also realized that in some data format, geom_rect (aes (xmin= ) works. Many thanks!!!! – Jin.w.Kim Jun 16 '21 at 13:21