我已經繪制了我的資料圖,但希望以百分比形式堆疊條形(資料總和為 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()
我也嘗試過 Melt 將資料更改為長格式,但我仍然無法使繪圖看起來正確。我哪里錯了?注意:我已經查看了其他答案,沒有一個涉及我需要的方面。
library(reshape2)
TestDataMelted <- melt(TestData, id=c("Stroke", "Ethnicity"))
uj5u.com熱心網友回復:
問題是你映射Stroke到x. 因為你只想要一個堆疊的條形圖x,例如一個常量,factor(1)并使用主題選項來擺脫 y 軸文本和刻度:
library(ggplot2)
ggplot(TestData, aes(
x = factor(1),
y = Percent,
label = scales::percent(Percent),
fill = as.factor(Stroke)
))
geom_col(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),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
labs(x = NULL, y = NULL, title = "Stroke among different ethnicities")
theme(plot.title = element_text(hjust = 0.5, size = 10, face = "bold"))
coord_flip()

uj5u.com熱心網友回復:
這是與親愛的@stefan 略有不同的方法。這里我們使用x="":
library(tidyverse)
TestData %>%
ggplot(aes(x = "", y= Percent, fill=factor(Stroke), label = scales::percent(Percent)))
geom_col(position = position_stack())
facet_wrap(~ Ethnicity, ncol = 3, strip.position = "bottom")
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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/391182.html
下一篇:如何在r中將長表轉換為寬表?
