這是我的資料框 - data_long1
data.frame(
value = c(88, 22, 100, 12, 55, 17, 10, 2, 2),
Subtype = as.factor(c("lung","prostate",
"oesophagus","lung","prostate","oesophagus","lung",
"prostate","oesophagus")),
variable = as.factor(c("alive","alive",
"alive","dead","dead","dead","uncertain","uncertain",
"uncertain"))
)
以下代碼為我提供了一個我想要的漂亮圖表,顯示了所有值,但沒有百分比。
ggplot(data_long1, aes(x = Subtype, y = value, fill = variable)) geom_bar(stat = "identity")
geom_text(aes(label= value), size = 3, hjust = 0.1, vjust = 2, position = "stack")
我正在尋找的是一個堆積條形圖,其中 Y 軸上顯示的實際值不是百分比(如上圖),但實際條形圖的每個小節上也顯示一個百分比圖。我嘗試這段代碼并得到一個毫無意義的圖表,每個堆疊都是 33.3%。
data_long1 %>% count(Subtype, variable) %>% group_by(Subtype) %>% mutate(pct= prop.table(n) * 100) %>% ggplot() aes(x = Subtype, y = variable, fill=variable)
geom_bar(stat="identity") ylab("Number of Patients")
geom_text(aes(label=paste0(sprintf("%1.1f", pct),"%")), position=position_stack(vjust=0.5)) ggtitle("My Tumour Sites") theme_bw()
我似乎找不到使用 mutate 函式來解決此問題的方法。請幫忙。
uj5u.com熱心網友回復:
我會預先計算你想要的摘要。這是每個子型別中的比例:
data_long2 <- data_long1 %>%
group_by(Subtype) %>%
mutate(proportion = value / sum(value))
ggplot(data_long2, aes(x = Subtype, y = value, fill = variable))
geom_bar(stat = "identity")
geom_text(aes(label= sprintf('%0.0f%%', proportion * 100)), size = 3, hjust = 0.1, vjust = 2, position = "stack")

group_by您還可以通過洗掉陳述句來獲得所有組和型別的比例:
data_long2 <- data_long1 %>%
mutate(proportion = value / sum(value))
ggplot(data_long2, aes(x = Subtype, y = value, fill = variable))
geom_bar(stat = "identity")
geom_text(aes(label= sprintf('%0.0f%%', proportion * 100)), size = 3, hjust = 0.1, vjust = 2, position = "stack")

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443278.html
上一篇:在一張圖上繪制超過2個圖
下一篇:合并來自兩個不同資料集的圖表
