我正在努力使用facet_grid()和facet wrap()使用ggplot(). 我希望能夠為每兩個類別(Department此處的變數)包裝不同的堆疊條形圖,但同時具有相同寬度的條形圖。第一個動作可以用 來實作,facet wrap()而第二個動作可以用來實作facet_grid()。我想結合這兩個功能的優點。您對如何解決問題有任何想法嗎?
資料是:
ID<-c("001","002","003","004","005","006","007","008","009","010","NA","012","013")
Name<-c("Damon Bell","Royce Sellers",NA,"Cali Wall","Alan Marshall","Amari Santos","Evelyn Frye","Kierra Osborne","Mohammed Jenkins","Kara Beltran","Davon Harmon","Kaitlin Hammond","Jovany Newman")
Sex<-c("Male","Male","Male",NA,"Male","Male",NA,"Female","Male","Female","Male","Female","Male")
Age<-c(33,27,29,26,27,35,29,32,NA,25,34,29,26)
UKCountry<-c("Scotland","Wales","Scotland","Wales","Northern Ireland","Wales","Northern Ireland","Scotland","England","Northern Ireland","England","England","Wales")
Department<-c("Sports and travel","Sports and travel","Sports and travel","Health and Beauty Care","Sports and travel","Home and lifestyle","Sports and travel","Fashion accessories","Electronic accessories","Electronic accessories","Health and Beauty Care","Electronic accessories",NA)
代碼是:
data<-data.frame(ID,Name,Sex,Age,UKCountry,Department)
## Frequency Table
dDepartmentSexUKCountry <- data %>%
filter(!is.na(Department) & !is.na(Sex) & !is.na(UKCountry)) %>%
group_by(Department,Sex,UKCountry) %>%
summarise(Count = n()) %>%
mutate(Total = sum(Count), Percentage = round(Count/Total,3))
## Graph
dSexDepartmentUKCountry %>%
ggplot(aes(x=Sex,
y=Percentage,
fill=UKCountry))
geom_bar(stat="identity",
position="fill")
geom_text(aes(label = paste0(round(Percentage*100,0),"%\n(", Count, ")")),
position=position_fill(vjust=0.5), color="white")
theme(axis.ticks.x = element_blank(),
axis.text.x = element_text(angle = 45,hjust = 1))
#facet_grid(cols = vars(Department),scales = "free", space = "free")
facet_wrap(. ~ Department, scales = "free", ncol = 2)
使用時facet_wrap(),我得到:

使用時facet_grid(),我得到:

理想情況下,我希望擁有(在 Paint 上編輯):

我已經研究了我的問題,并且經常會找到一種或另一種解決方案,但不會同時找到兩者的組合。
uj5u.com熱心網友回復:
以下是否可以接受?

我通過scales = "free"從facet_wrap(). 列的寬度相同。您可能更喜歡沒有開放空間,其中一種性別確實有該部門的任何資料。但是,我認為這更容易閱讀,因為類別軸標簽在每個地塊上都位于同一位置(左側為女性,右側為男性),并且該圖清楚地傳達了某些部門女性或男性客戶不購買的資訊。
這是代碼:
dDepartmentSexUKCountry %>%
ggplot(aes(x=Sex,
y=Percentage,
fill=UKCountry))
geom_bar(stat="identity",
position="fill")
geom_text(aes(label = paste0(round(Percentage*100,0),"%\n(", Count, ")")),
position=position_fill(vjust=0.5), color="white")
theme(axis.ticks.x = element_blank(),
axis.text.x = element_text(angle = 45,hjust = 1))
facet_wrap(. ~ Department, ncol = 2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420819.html
標籤:
