【问题标题】:Draw two groups of multiple vertical lines in ggplot在ggplot中绘制两组多条垂直线
【发布时间】:2019-06-17 20:42:18
【问题描述】:

我想用下面的r函数在ggplot中画出a1, a2b1, b2这两组垂直线。

myline = data.frame(vv = c(a1 = 25, a2 = 28, b1 = 52, b2 = 53))


set.seed(100)
d = data.frame(y = c(rnorm(100,5,1), rnorm(100, 2,4)), x = 1:200)
ggplot(data = d) + geom_line(aes(x, y), color = "steelblue") + 
  geom_vline(data = myline, aes(xintercept=as.numeric(vv)), col= 'red', size = 0.8)

我正在尝试以不同的颜色分隔 ab 组。我怎样才能做到这一点?非常感谢您的建议。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    要获得不同颜色的垂直线,请在对geom_vline 的调用中使用vv 作为颜色。然后使用scale_color_manual 设置选择的颜色。
    另请注意,在为xintercept 美学设置值时,不需要as.numeric(vv)str(myline) 将显示vv 已经是数字。

    ggplot(data = d, aes(x, y)) + 
      geom_line(color = "steelblue") + 
      geom_vline(data = myline, 
                 aes(xintercept = vv, color = factor(vv)),
                 size = 0.4) +
      scale_color_manual(values = c("coral", "coral4", "orange", "orange4"))
    

    【讨论】:

      【解决方案2】:

      这就是你所追求的吗?

      library("dplyr")
      
      myline = data.frame(vv = c(25, 28, 52, 53),
                          xx = c("a1", "a2", "b1", "b2"))
      
      myline <- as_tibble(myline) %>%
        mutate(group = substr(xx,1,1))
      
      set.seed(100)
      d = data.frame(y = c(rnorm(100,5,1), rnorm(100, 2,4)), x = 1:200)
      
      ggplot(data = d) + geom_line(aes(x, y), color = "steelblue") + 
        geom_vline(data = myline, aes(xintercept=as.numeric(vv), col=group), size = 0.8)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        相关资源
        最近更新 更多