ggplot中的垂直线

时间:2018-10-15 15:01:34

标签: r ggplot2

有人知道为什么我在ggplot的col4上只绘制一条垂直线时为什么在ggplot的其他列上得到多行吗?

library(tidyr)
library(dplyr)
library(ggplot2)

Col0 <- c("AA", "BB", "CC", "DD","EE","FF")
Col1 <- c(2,2,2,6,1,1)
Col2 <- c(2,2,2,1,3,4)
Col3 <- c(2,2,3,4,6,6)
Col4 <- c(2,2,3,1,2,1)
Col5 <- c(2,1,1,1,1,4)
Col6 <- c(2,4,2,5,4,4)
Col7 <- c(2,4,2,5,4,4)
Col8 <- c(2,2,3,4,5,4)
Col9 <- c(1,3,3,2,2,2)
df<-data.frame(Col0,Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8,Col9)


plotDat <- df %>%
  gather(Col, Val, -Col0)%>%
  split(Col0)

pdf("plots.pdf")
lapply(names(plotDat), function(i){
  ggplot(plotDat[[i]], aes(Col, Val, group = Col0, col = Col0)) +
    geom_line() +
    geom_vline(xintercept = Col4) +
    geom_vline(xintercept = Col4, linetype="dotted", color = "blue", size=1.5)+
    ggtitle(paste("Plot", i))
  })
dev.off()

enter image description here

1 个答案:

答案 0 :(得分:1)

如果要在(离散)x轴的第4个中断处显示Vline,请设置xintercept = 4

因此,在两行Col4中将4替换为geom_vline

pdf("plots.pdf")
lapply(names(plotDat), function(i){
  ggplot(plotDat[[i]], aes(Col, Val, group = Col0, col = Col0)) +
    geom_line() +
    geom_vline(xintercept = 4) +
    geom_vline(xintercept = 4, linetype="dotted", color = "blue", size=1.5)+
    ggtitle(paste("Plot", i))
})
dev.off()

enter image description here