【问题标题】:How to draw multiple line segment in ggplot如何在ggplot中绘制多条线段
【发布时间】:2020-06-23 22:08:30
【问题描述】:
#Input data
df1<- data.frame(Gradient=rep(c(0,5,10,15), each=5),
                 load=c(0,4.4,10.7,17,21.4),
                vo2max=c(28.0,28.2,31.0,32.0,34.6,41.0,41.1,45.4,48.8,50.5,56.3,57.0,
                         63.6,66.8,69.9,71.3,75.0,82.1,85.5,89.3))
head(df1)
sp<-ggplot(data=df1, aes(x=load, y=VO2max, group=Gradient)) +
  geom_line()+
  geom_point()
#Horizontal line segment
sp+geom_segment(aes(x=0,y=50,xend=25,yend=50))
sp+geom_segment(aes(x=0,y=60,xend=25,yend=60))``
sp+geom_segment(aes(x=0,y=75,xend=25,yend=75))

如何在同一张图中画出三个线段? 我一次只能绘制一条线段。

【问题讨论】:

  • (1)VO2maxvo2max给我们可用的代码。 (2)sp+geom_segment(...)+geom_segment(...)+geom_segment(...)?

标签: r ggplot2


【解决方案1】:

将数据放入data.frame:

line_df <- data.frame(
  x = 0,
  y = c(50, 60, 75),
  xend = 25,
  yend = c(50, 60, 75)
)

sp +
  geom_segment(
    data = line_df, 
    mapping = aes(x=x, y=y, xend=xend, yend=yend), 
    inherit.aes = FALSE
  )

【讨论】:

    【解决方案2】:

    只需将它们加在一起即可。

    sp +
      geom_segment(aes(x=0,y=50,xend=25,yend=50)) +
      geom_segment(aes(x=0,y=60,xend=25,yend=60)) +
      geom_segment(aes(x=0,y=75,xend=25,yend=75))
    

    【讨论】:

      【解决方案3】:
      ggplot(data=df1, aes(x=load, y=vo2max, group=Gradient)) +
        geom_line()+
        geom_point() + 
        geom_segment(
          data=tibble(), 
          aes(
            x=c(0, 0, 0),
            y=c(50, 60, 75),
            xend=c(25, 25, 25),
            yend=c(50, 60, 75)
          ), 
          inherit.aes=FALSE
        )
      

      也可以考虑geom_hline()

      【讨论】:

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