2016-03-07 38 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