geom_vline 不适用于我的箱线图

geom_vline does not work on my boxplot

我创建了多面箱线图。现在我需要在情节上添加线条。该行没有出现在我下面的代码中。请给我一些帮助!谢谢!

数据:

Year    |variable   |value
2001    |A          |39.605
2001    |A          |28.50759
2001    |A          |24.8132
2002    |A          |10.70765357
2002    |A          |7.8676
2002    |A          |16.05294712
2003    |A          |19.7847
2003    |A          |20.21635
2003    |A          |29.15491667
2001    |B          |50
2001    |B          |78
2001    |B          |90
2002    |B          |35
2002    |B          |62
2002    |B          |82.5
2003    |B          |49.5
2003    |B          |60
2003    |B          |84

代码:

pp <- ggplot(dta, aes(x=factor(Year),y=value)) +
  geom_boxplot() +
  facet_grid(variable~.,scales="free_y") +
  theme_bw()
pp + geom_vline(xintercept = 2002) #The line didn't show.
pp + geom_vline(xintercept = as.numeric(2002)) #The line didn't show.
pp + geom_vline(xintercept = which(levels(dta$Year) =="2002")) #The line didn't show.

知道了! pp + geom_vline(x截距 = 2)

请试试

pp + geom_vline(xintercept = which(levels(factor(dta$Year)) =="2002"))

您指定了aes(x=factor(Year),...,所以您需要找到因子水平的整数。 levels(dta$Year) returns NULL 因为 Year 不是原始数据帧 dta 中的一个因素。因此,您需要在对 geom_vline():

的调用中添加 factor(dta$Year)
levels(factor(dta$Year))
#[1] "2001" "2002" "2003"

请注意,即使您更改了输入数据,这与在 中硬编码特定因子水平相反,这仍然有效。