在stat_bin ggplot中使用自定义标签

时间:2017-10-13 03:09:06

标签: r ggplot2

以下代码创建一个直方图,并将计数标签放在每个条上。

breaks=seq(0,100,by=10)
ggplot(df, aes(x=spread,y=..count../sum(..count..))) +
  stat_bin(breaks=breaks,fill='red',colour='black')+
 stat_bin(breaks=breaks,geom='text',aes(label=..count..),vjust=-1.5,pad=FALSE)+
  scale_x_continuous(breaks=breaks)

有10个箱子,我想在每个栏上放置我自己的(不计数)标签 ,例如

my_label=log(1:10) #Could be anything here
ggplot(df, aes(x=spread,y=..count../sum(..count..))) + 
  stat_bin(breaks=breaks,fill='red',colour='black')+
  stat_bin(breaks=breaks,geom='text',aes(label=my_label),vjust=-1.5,pad=FALSE)+
  scale_x_continuous(breaks=breaks)

如果我这样做,我会收到错误: Error: Aesthetics must be either length 1 or the same as the data (847): label, x

有简单的方法吗?我知道有些人建议使用dplyr包并修改数据帧(df),基本上创建原始数据帧统计数据的数据帧。还有什么比这简单吗?毕竟,我们使用直方图绘制来避免自己执行分箱和统计。

1 个答案:

答案 0 :(得分:0)

library(ggplot2)
set.seed(1)
breaks <- seq(0,100,by=10)
df <- data.frame(spread = rnorm(1000,50,10))
my_label <- letters[1:10] #Could be anything here
ggplot(df, aes(x=spread,y=..count../sum(..count..))) + 
  stat_bin(breaks=breaks,fill='red',colour='black')+
  stat_bin(breaks=breaks,geom='text',label=my_label,vjust=-1.5,pad=FALSE)+
  scale_x_continuous(breaks=breaks)

enter image description here

修改
以下是@ user5768239提出的进一步问题的解决方案:
有没有办法删除..count .. == 0?

的标签
breaks <- seq(0,100,by=10)
set.seed(123)
df <- data.frame(spread = rnorm(1000,40,8))
spread_cat <- cut(df$spread, breaks=breaks)
tbl <- table(spread_cat)
my_label <- letters[1:10] #Could be anything here
my_label[tbl==0] <- ""
ggplot(df, aes(x=spread,y=..count../sum(..count..))) + 
  stat_bin(breaks=breaks,fill='red',colour='black')+
  stat_bin(breaks=breaks,geom='text',label=my_label,vjust=-1.5,pad=FALSE)+
  scale_x_continuous(breaks=breaks)

enter image description here