在ggplot中的条形图上添加自定义标签

时间:2016-03-07 12:50:42

标签: r ggplot2 bar-chart labels

我正在ggplot2中绘制一个简单的条形图,我需要在图的每个条上显示与我使用的数据集无关的东西(数字或字符串......)。 例如,使用以下说明:

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 个答案:

答案 0 :(得分:2)

问题在于您使用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

相关问题