【发布时间】:2022-01-24 07:38:54
【问题描述】:
我已经绘制了我的数据图,但希望条形按百分比堆叠(数据总和已达到 100%)。
TestData <- tibble(Ethnicity = c(rep("Black",2), rep("Asian",2), rep("White",2)),
Stroke = c(0,1,0,1,0,1),
Percent = c(0.33, 0.67, 0.50, 0.50, 0.20, 0.80))
所以,我只想要一个用于变量 Stroke 的条形
ggplot(TestData, aes(x=as.factor(Stroke),
y=Percent,
label = scales::percent(Percent),
fill = as.factor(Stroke) ) ) +
geom_bar(stat="identity", position="stack") +
facet_wrap(~ Ethnicity, ncol = 3, strip.position = "bottom")+
scale_y_continuous(labels = scales::percent)+
scale_fill_manual(values = c("#1380A1", "#FAAB18")) +
geom_text(position = position_stack(vjust=0.5), colour="white", size = 3) +
theme_bw() +
theme(legend.position="none") +
theme(axis.text.x = element_text(size=8)) +
xlab("") +
ylab("") +
ggtitle("Stroke among different ethnicities") +
theme(plot.title = element_text(hjust = 0.5, size=10, face="bold")) +
coord_flip()
我也尝试过将数据更改为长格式,但我仍然无法让绘图看起来正确。我哪里错了?注意:我已经查看了其他答案,没有一个涉及我需要的方面。
library(reshape2)
TestDataMelted <- melt(TestData, id=c("Stroke", "Ethnicity"))
【问题讨论】: