Histogram ggplot:显示每个类别的每个bin的计数标签

Nad*_*ham 11 r ggplot2

我将使用ggplot中的钻石数据集来说明我的观点,我想绘制一个直方图的价格,但我想显示每个切割的每个切割的计数这是我的代码

ggplot(aes(x = price ) , data = diamonds_df) + 
geom_histogram(aes(fill = cut , binwidth = 1500)) +
stat_bin(binwidth= 1500, geom="text", aes(label=..count..) , 
vjust = -1) + 
scale_x_continuous(breaks = seq(0 , max(stores_1_5$Weekly_Sales) , 1500 ) 
, labels = comma)
Run Code Online (Sandbox Code Playgroud)

这是我目前的情节

在此输入图像描述

但是当你看到数字显示每个箱子上所有切口的数量时,我想显示每个箱子上每个切口的数量.

如果我能够配置Y轴而不是在步骤5000显示数字我可以手动配置的其他东西也是一个奖励点

eip*_*i10 17

更新ggplot22.x.

您现在可以将标签置于堆叠条形图中,而无需使用预先汇总数据position=position_stack(vjust=0.5).例如:

ggplot(aes(x = price ) , data = diamonds) + 
  geom_histogram(aes(fill=cut), binwidth=1500, colour="grey20", lwd=0.2) +
  stat_bin(binwidth=1500, geom="text", colour="white", size=3.5,
           aes(label=..count.., group=cut), position=position_stack(vjust=0.5)) +
  scale_x_continuous(breaks=seq(0,max(diamonds$price), 1500))
Run Code Online (Sandbox Code Playgroud)

原始答案

你可以得到的每一个值的计数cut通过添加cut作为group审美stat_bin.我也搬到了binwidth外面aes,这导致binwidth你的原始代码被忽略了:

ggplot(aes(x = price ), data = diamonds) + 
  geom_histogram(aes(fill = cut ), binwidth=1500, colour="grey20", lwd=0.2) +
  stat_bin(binwidth=1500, geom="text", colour="white", size=3.5,
           aes(label=..count.., group=cut, y=0.8*(..count..))) +
  scale_x_continuous(breaks=seq(0,max(diamonds$price), 1500))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

上面代码的一个问题是我希望标签在每个条形区域内垂直居中,但我不确定如何在内部进行stat_bin,或者甚至可能.乘以0.8(或其他)将每个标签移动不同的相对量.因此,为了使标签居中,我在下面的代码中为标签创建了一个单独的数据框:

# Create text labels
dat = diamonds %>% 
  group_by(cut, 
           price=cut(price, seq(0,max(diamonds$price)+1500,1500),
                     labels=seq(0,max(diamonds$price),1500), right=FALSE)) %>%
  summarise(count=n()) %>%
  group_by(price) %>%
  mutate(ypos = cumsum(count) - 0.5*count) %>%
  ungroup() %>%
  mutate(price = as.numeric(as.character(price)) + 750)

ggplot(aes(x = price ) , data = diamonds) + 
  geom_histogram(aes(fill = cut ), binwidth=1500, colour="grey20", lwd=0.2) +
  geom_text(data=dat, aes(label=count, y=ypos), colour="white", size=3.5)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

要在y轴上配置中断,只需添加scale_y_continuous(breaks=seq(0,20000,2000))或任何您想要的中断.