有没有办法限制ggplot2中的vline长度

时间:2012-01-31 18:46:05

标签: r ggplot2

我正在尝试使用ggplot vline和hline在线图上显示截距,但是希望线条在图形上的拦截点停止。这可能在ggplot中还是有其他解决方案

library(ggplot2)

pshare <- data.frame()

for (i in 1:365) {
  pshare <- rbind(pshare,c(i, pbirthday(i,365,coincident=3)))
}

names(pshare) <- c("number","probability")

x25 <- qbirthday(prob = 0.25, classes = 365, coincident = 3) #61
x50 <- qbirthday(prob = 0.50, classes = 365, coincident = 3)
x75 <- qbirthday(prob = 0.75, classes = 365, coincident = 3)

p <- qplot(number,probability,data=subset(pshare,probability<0.99))

p <- p + geom_vline(xintercept = c(x25,x50,x75))
p <- p + geom_hline(yintercept = c(0.25,0.5,0.75))
p

所以,例如,我希望0.25 / 61线在他们在情节上相遇时结束

TIA

1 个答案:

答案 0 :(得分:23)

将@joran的评论扩展为答案和示例

geom_vline画了整个情节;这是它的目的。 geom_segment只会在特定的终点之间划分。它有助于使用相关信息创建数据框以绘制线条。

probs <- c(0.25, 0.50, 0.75)
marks <- data.frame(probability = probs,
                    number = sapply(probs, qbirthday, classes=365, coincident=3))

通过这种方式,使线条更容易进入十字路口。

qplot(number,probability,data=subset(pshare,probability<0.99)) +
  geom_segment(data=marks, aes(xend=-Inf, yend=probability)) +
  geom_segment(data=marks, aes(xend=number, yend=-Inf))

enter image description here