簡體   English   中英

如何在y軸為“ count”的ggplot中的堆疊條形圖中繪制標簽?

[英]How to position your labels in stacked bar graph plot in ggplot where the y axis is “count”?

默認以x軸作為名稱(分類)和y軸繪制ggplot

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!

這就是我對ggplot的看法

(它們的位置不正確。位置需要調換並居中) 在此處輸入圖片說明

您可以在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM