2012-09-22 36 views
12

我有一些數據用於繪製直方圖。我也有兩套具有一定意義的門檻。將vline添加到現有繪圖並使其出現在ggplot2圖例中?

我可以用適當的樣式繪製直方圖和曲線。但是,我無法讓我的vlines顯示在圖例中。我相信像這樣的東西應該可以工作,但是圖例項目不會顯示。

df <- data.frame(val=rnorm(300, 75, 10)) 

cuts1 <- c(43, 70, 90) 
cuts2 <- c(46, 79, 86) 

ggplot(data=df, aes(x=val)) + 
    geom_histogram() + 
    geom_vline(xintercept=cuts1, 
      linetype=1, 
      color="red", 
      labels="Thresholds A", 
      show_guide=TRUE) + 
    geom_vline(xintercept=cuts2, 
      linetype=2, 
      color="green", 
      labels="Thresholds B", 
      show_guide=TRUE) 

或者,如果我構建了我的裁減data.frame,做一個審美的映射,我可以讓我vlines在傳說中出現。不幸的是,傳說給我彼此疊加不同的行類型的兩個實例:

cuts1 <- data.frame(Thresholds="Thresholds A", vals=c(43, 70, 90)) 
cuts2 <- data.frame(Thresholds="Thresholds B", vals=cuts2 <- c(46, 79, 86)) 

ggplot(data=df, aes(x=val)) + 
    geom_histogram() + 
    geom_vline(data=cuts1, aes(xintercept=vals, shape=Thresholds), 
      linetype=1, 
      color="red", 
      labels="Thresholds A", 
      show_guide=TRUE) + 
    geom_vline(data=cuts2, aes(xintercept=vals, shape=Thresholds), 
      linetype=2, 
      color="green", 
      labels="Thresholds B", 
      show_guide=TRUE) 

enter image description here

那麼,到底是什麼我要找的,是最簡單的方法手動將兩組線條添加到圖中,然後讓它們在圖例中正確顯示。

回答

22

訣竅是把閾值數據都在相同數據幀,然後映射美學,而不是將它們設置:

cuts <- rbind(cuts1,cuts2) 

ggplot(data=df, aes(x=val)) + 
    geom_histogram() + 
    geom_vline(data=cuts, 
      aes(xintercept=vals, 
       linetype=Thresholds, 
       colour = Thresholds), 
      show_guide = TRUE) 

enter image description here

相關問題