Ant*_*ton 2 graphics r ggplot2
我想在 ggplot2 的堆积条形图上显示数据值。经过多次尝试,我发现显示总量(每个豆)的唯一方法是使用以下代码
set.seed(1234)
df <- data.frame(
sex=factor(rep(c("F", "M"), each=200)),
weight=round(c(rnorm(200, mean=55, sd=5), rnorm(200, mean=65, sd=5)))
)
p<-ggplot(df, aes(x=weight, fill=sex, color=sex))
p<-p + geom_histogram(position="stack", alpha=0.5, binwidth=5)
tbl <- (ggplot_build(p)$data[[1]])[, c("x", "count")]
agg <- aggregate(tbl["count"], by=tbl["x"], FUN=sum)
for(i in 1:length(agg$x))
if(agg$count[i])
p <- p + geom_text(x=agg$x[i], y=agg$count[i] + 1.5, label=agg$count[i], colour="black" )
Run Code Online (Sandbox Code Playgroud)
生成以下图:
有没有更好(更有效)的方法来使用 ggplot2 获得相同的结果?非常感谢提前
您可以使用stat_bin来计算值并添加文本标签。
p <- ggplot(df, aes(x=weight)) +
geom_histogram(aes(fill=sex, color=sex),
position="stack", alpha=0.5, binwidth=5) +
stat_bin(aes(y=..count.. + 2, label=..count..), geom="text", binwidth=5)
Run Code Online (Sandbox Code Playgroud)
我将fill和color美学移至 ,geom_histogram以便它们仅适用于该层而不是全局应用于整个图,因为我们希望stat_bin为每个 bin 生成和总体计数,而不是为每个级别的sex. ..count..是由stat_bin存储计数返回的内部变量。
在这种情况下,直接添加计数很简单。但是,在更复杂的情况下,您有时可能希望汇总 ggplot 之外的数据,然后将汇总数据提供给 ggplot。在这种情况下,您将如何执行此操作:
library(dplyr)
counts = df %>% group_by(weight = cut(weight, seq(30,100,5), right=FALSE)) %>%
summarise(n = n())
countsByGroup = df %>% group_by(sex, weight = cut(weight, seq(30,100,5), right=FALSE)) %>%
summarise(n = n())
ggplot(countsByGroup, aes(x=weight, y=n, fill=sex, color=sex)) +
geom_bar(stat="identity", alpha=0.5, width=1) +
geom_text(data=counts, aes(label=n, y=n+2), colour="black")
Run Code Online (Sandbox Code Playgroud)
或者,您可以直接创建countsByGroup然后counts在内部动态创建等效项ggplot:
ggplot(countsByGroup, aes(x=weight, y=n, fill=sex, color=sex)) +
geom_bar(stat="identity", alpha=0.5, width=1) +
geom_text(data=countsByGroup %>% group_by(weight) %>% mutate(n=sum(n)),
aes(label=n, y=n+2), colour="black")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2474 次 |
| 最近记录: |