【问题标题】:How to draw a box (or circle) to emphasize specific area of a graph in R?如何绘制一个框(或圆圈)以强调 R 中图形的特定区域?
【发布时间】:2021-09-01 04:40:37
【问题描述】:

如果我有如下条形图,

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 的图中画一个框来强调。你能告诉我如何在图表中画一个盒子或圆形(或其他形状)吗?

谢谢,

【问题讨论】:

    标签: r graph drawing box


    【解决方案1】:

    您应该通过将 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)
    

    【讨论】:

    • 完美运行!!!我还意识到,在某些数据格式中,geom_rect (aes (xmin=) 有效。非常感谢!!!!
    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 2013-09-20
    • 2014-04-11
    • 2012-09-19
    相关资源
    最近更新 更多