使用ggplot的连续和虚线

时间:2011-07-24 19:53:28

标签: r ggplot2

我有一组坐标

(x, y) = (0, 2), (1, 3), (1, 2), (2, 4)      (this is a simplified example)

每当y坐标增加时,我想用连续线加入坐标。每当y坐标减小时,我想用虚线加入坐标。在上面的例子中,

1。)坐标(0,2)和(1,3)用直线连接,

2。)坐标(1,3)和(1,2)用虚线连接,

3。)坐标(1,3)和(2,4)用直线连接。

是否可以在R中使用ggplot来做到这一点?到目前为止,我只能连续加入坐标线。 (如果这可能使任何事情变得更容易,那么当x坐标没有变化时,我只会减少y坐标。)

感谢您的帮助!

2 个答案:

答案 0 :(得分:7)

试试这个,

dat <- data.frame(x=c(0,1,1,2),y=c(2,3,2,4))

## add endpoints (xend, yend), and and id variable 
## tracking the sign of diff(y)
dat2 <- with(dat, data.frame(x=x[-length(x)], y=y[-length(y)],
                             id= diff(y) > 0,xend=x[-1], yend=y[-1]))

head(dat2)
ggplot(dat2) +
  geom_segment(aes(x=x, y=y, xend=xend, yend=yend, linetype=id)) +
  scale_linetype_manual(values=c("dashed", "solid"))

答案 1 :(得分:5)

(编辑删除一些可能具有误导性的陈述......)

感谢您提出这个问题!起初我觉得这会非常可怕,但后来我想起了一个关于如何在列表中存储一堆ggplot组件的小技巧,事实证明并不是那么糟糕:

#Your example data
dat <- data.frame(x=c(0,1,1,2),y=c(2,3,2,4))

#Initialize the list    
pathList <- vector("list",nrow(dat) - 1)
#Loop over the data and put the appropriate `geom_line` in each slot
for (i in 2:nrow(dat)){
    if (dat$y[i] - dat$y[i-1] >= 0){
        pathList[[i-1]] <- geom_line(data = dat[(i-1):i,],aes(x=x,y=y))
    }
    else{
        pathList[[i-1]] <- geom_line(data = dat[(i-1):i,],aes(x=x,y=y),
                                 linetype="dashed")
    }
}

p <- ggplot(data=dat,aes(x=x,y=y)) + pathList

导致了这个:

enter image description here

正如评论中所指出的,这种解决方案效率很低......

相关问题