使用ggplot2和GGally,我用比例創建了這個條形圖:

ggplot(mtcars, aes(x = factor(cyl), by = 1))
geom_bar(fill = "steelblue", stat = "prop")
geom_text(aes(label = scales::percent(after_stat(prop), accuracy = 1)), stat = "prop", nudge_y = 0.5)
theme_minimal()
theme(aspect.ratio = 1.5)
但是,在 y 軸上,我想對其進行更改以反映條形圖上的百分比。我想避免硬編碼像 ylim = "40" 這樣的值,但讓它使用圖表中的值。
uj5u.com熱心網友回復:
試試這個:
ggplot(mtcars, aes(x = cyl))
geom_bar(aes(y = ..prop..), fill = "steelblue", stat = "count")
geom_text(aes(label = scales::percent(..prop..), y = ..prop.. ), stat= "count", vjust = -.5)
ylim(0, 0.5)
ylab("")
theme_minimal()
theme(aspect.ratio = 1.5)
編輯:如果你想要x軸上的一個因素嘗試
ggplot(mtcars, aes(x = factor(cyl)))
geom_bar(aes(y = (..count..)/sum(..count..)), fill = "steelblue", stat = "count")
geom_text(aes(label = scales::percent(round((..count..)/sum(..count..), 2)),
y = ((..count..)/sum(..count..))), stat = "count", vjust = -.25)
ylim(0, 0.5)
ylab("")
theme_minimal()
theme(aspect.ratio = 1.5)
Edit2:使用GGally您可以使用的包:
ggplot(mtcars, aes(x = factor(cyl), by = 1))
geom_bar(aes(y = ..prop..), fill = "steelblue", stat = "prop")
geom_text(aes(label = scales::percent(..prop..), y = ..prop.. ), stat = "prop", vjust = -.5)
ylim(0, 0.5)
ylab("")
theme_minimal()
theme(aspect.ratio = 1.5)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/384679.html
