【问题标题】:Histogram ggplot : Show count label for each bin for each category直方图 ggplot :显示每个类别的每个 bin 的计数标签
【发布时间】:2015-07-15 11:16:49
【问题描述】:

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

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)

这是我目前的情节

但正如您看到的,数字显示了每个箱中所有切割的计数,我想显示每个箱上每个切割的计数。

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

【问题讨论】:

  • 所以你想把五个数字挤进每个箱子里?是的,那看起来会很漂亮......
  • 是的,完全正确:)

标签: r ggplot2


【解决方案1】:

ggplot2 2.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))

原答案

您可以通过将cut 作为group 美学添加到stat_bin 来获取cut 的每个值的计数。我还将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))

上面代码的一个问题是,我希望标签在每个条形部分中垂直居中,但我不确定如何在 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)

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

【讨论】:

    【解决方案2】:

    现在有了 GGPLOT 2.2.0 position_stack 选项让事情变得更容易

    library(ggplot2)
    s <- ggplot(mpg, aes(manufacturer, fill = class))
    s + geom_bar(position = "stack") +  
        theme(axis.text.x = element_text(angle=90, vjust=1)) + 
        geom_text(stat='count', aes(label=..count..), position = position_stack(vjust = 0.5),size=4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-26
      • 2014-09-29
      • 1970-01-01
      • 2019-06-04
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多