如何绘制一个框(或圆圈)以强调 R 中图形的特定区域?

How to draw a box (or circle) to emphasize specific area of a graph in R?

如果我有如下的条形图,

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)

我想在d和e的图中画一个方框来强调。你能告诉我如何在图表中画一个方框或圆圈(或其他形状)吗?

谢谢,

您应该通过将 x 列的类型设置为 factor 并使用 geom_rect() 将矩形层添加到 ggplot 来实现您在这种特定情况下寻找的内容。 geom_rect 函数中的 Linetype = 8 给出了您提供的图中的虚线。下面的代码采用了这种方法。另一个允许添加矩形的函数是 annotate(),它也支持其他类型的注释。具体关于圈子,这已经存在: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)