我希望能够创建堆叠的条形图,但是当我更改stat =“ identity”时出现错误: “ FUN(X [[i]]中的错误,... ):找不到对象“ prop””
这是我的代码:
ggplot(data = wq,aes(x=WHO_Risk_Level,group=1))+
geom_bar(aes(y=..prop..,fill=factor(..x..)),stat ="count")+
labs(y="Percent",x="WHO Risk Level")+
scale_y_continuous(labels = scales::percent_format())+
guides(
fill=FALSE
)
答案 0 :(得分:0)
我认为您需要的参数是position =“ stack”。 stat =“ identity”将使条形图成为y轴上事物的计数,而stat =“ bin”则类似于直方图。在geom_bar()中尝试position =“ stack” 在我看来,position =“ dodge”是此处的默认设置
ggplot(data = wq,aes(x=WHO_Risk_Level,group=1))+
geom_bar(aes(y=..prop..,fill=factor(..x..)),stat ="count", position = "stack")+
labs(y="Percent",x="WHO Risk Level")+
scale_y_continuous(labels = scales::percent_format())+
guides(
fill=FALSE
)
答案 1 :(得分:0)
当您指定x为因子时,我认为您无法将其堆叠。一种先计数并绘图的方法:
set.seed(111)
wq = data.frame(WHO_Risk_Level=sample(c("High","Intermediate","Low"),1000,
prob=c(0.25,0.35,0.4),replace=TRUE))
library(dplyr)
wq %>%
count(WHO_Risk_Level) %>%
mutate(proportion=100*n/sum(n)) %>% ggplot(aes(x=1,y=proportion,fill=WHO_Risk_Level)) +
geom_bar(stat="identity") +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())