2017-03-01 23 views
0

我創建了一個多面箱線。現在我需要在情節中添加線條。下面的代碼沒有顯示該行。請給我一些幫助!謝謝!geom_vline無法在我的箱子上工作

數據:

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. 

回答

0

請嘗試

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

您指定了aes(x=factor(Year),...,所以你需要找到因子水平的整數倍。 levels(dta$Year)返回NULL,因爲Year不是原始數據幀dta中的因子。所以,您需要在您的通話添加factor(dta$Year)geom_vline()

levels(factor(dta$Year)) 
#[1] "2001" "2002" "2003" 

請注意,如果你改變你的輸入數據,而不是硬編碼特定因子水平像your own answer這會甚至工作。

+0

非常感謝 - Uwe!你的答案可以幫助我理解levels()函數,並在未來更好地使用它! – Angel

+0

@Angel我很高興能夠幫到你。也許,你可能想考慮[this](http://stackoverflow.com/help/someone-answers)? – Uwe

0

明白了! PP + geom_vline(xintercept = 2)