更新为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
通过增加cut
as a 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))
上面代码的一个问题是我希望标签在每个条形部分中垂直居中,但我不确定如何在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))
或者任何你想要的中断。