2016-03-07 77 views
1

我正在ggplot2中繪製一個簡單的barplot,並且需要在該圖的每個條上顯示與該數據集I無關的內容(數字或字符串..)正在使用。 例如有以下說明:在ggplot的條上添加自定義標籤

ggplot(diamonds,aes(cut))+geom_bar() 

我得到這個圖:

enter image description here

而且我想顯示,在酒吧,在數組中的元素:

val<-c(10,20,30,40,50) 

獲取像這樣的結果其他圖

enter image description here

我試圖以這種方式使用geom_text

ggplot(diamonds,aes(cut))+geom_bar()+ 
geom_text(aes(label=val)) 

,但我得到了以下錯誤消息

Error: Aesthetics must be either length 1 or the same as the data (53940): label, x 
+1

看[這裏](http://stackoverflow.com/questions/22777245 /如何到添加定製的標籤,從-A-數據集上,頂級的酒吧 - 使用 - ggplot-GEOM的酒吧中) –

回答

1

的問題是,你是一個直方圖geom_bar有是否指定了y變量。爲了應用this example,你需要總結cut變量第一:

val<-c(10,20,30,40,50) 

library(dplyr) 
diamonds %>% 
    group_by(cut) %>% 
    tally() %>% 
    ggplot(., aes(x = cut, y = n)) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label = val), vjust = -0.5, position = position_dodge(0.9)) 

它給你:

enter image description here