[英]How to position your labels in stacked bar graph plot in ggplot where the y axis is “count”?
gnew = ggplot(data= got, aes(x= got$attacker_king, fill= got$attacker_outcome))+
geom_bar() +
geom_text(stat = "count", aes(label =..count..), vjust = -.5)+
scale_y_continuous(limits = c(0,20)) # plotting the stacked ggplot #this works
got = ddply(got, .(got$attacker_king),
transform, pos = cumsum(..count..)- (0.5 *..count..)) # positioning labels shows error
#This shows error as "Error in eval(expr, envir, enclos) : object '..count..' not found"
Please help!
您可以在geom_text()
調用中使用position=position_stack(vjust=0.5)
。
使用iris
數據集的示例。
library(ggplot2)
ggplot(data= iris, aes(x= Sepal.Width, fill= Species))+
geom_bar() +
geom_text(stat = "count", aes(label =..count..), position=position_stack(vjust=0.5))+
scale_y_continuous(limits = c(0,20))
根據如何計算百分比的要求進行編輯 。
library(ggplot2)
library(dplyr)
summary<-as.data.frame(iris %>%
group_by(Species,Sepal.Width) %>%
tally %>%
group_by(Sepal.Width) %>%
mutate(pct=(100*n)/sum(n)))
ggplot(data= summary, aes(x= Sepal.Width, y=n,fill= Species))+
geom_bar(stat='identity') +
geom_text(aes(label =round(pct,2)), position=position_stack(vjust=0.5),size=3)+
scale_y_continuous(limits = c(0,20))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.