我有一個包含三個變數的 ggplot:辦公室、級別和性別。該地塊應按辦公室和級別進行考慮,并顯示每個辦公室的級別和性別代表性。我按照我想要的方式處理情節沒有問題,但我無法創建 x 軸文本來顯示每個辦公室的級別——x 軸下顯示的所有內容都是辦公室名稱,這使得它無法區分不同級別的條形(我用不同顏色處理的性別不是問題,除非有人是色盲......)。我已經編輯了標題、xLab、yLab 等的行以專注于這個問題。感謝您的幫助!
這是我的資料:
#A tibble: 20 x 4
office level gender count
1 office1 A Female 3
2 office1 A Male 1
3 office1 B Female 11
4 office1 B Male 9
5 office1 C Female 16
6 office1 C Male 13
7 office1 C Other 2
8 office1 D Female 16
9 office1 D Male 11
10 office1 D Female 6
11 office1 D Male 10
12 office1 D Other 1
13 office2 A Male 1
14 office2 A Female 3
15 office2 B Male 1
16 office2 B Female 12
17 office2 B Male 3
18 office2 B Female 1
19 office2 D Male 5
20 office2 D Male 1
這是我的代碼:
myBarChart <- function(data,var1,var2,var3,count,factor1, factor2) {
# the following code creates the tibble above when I run the function:
fields <- c(var1,var2,var3)
data <- df[ ,fields]
data[[var1]] <- factor(data[[var1]], levels = factor1)
data[[var2]] <- factor(data[[var2]], levels = factor2)
data <- data %>% group_by_at(fields) %>% summarize(count = n())
data <- filter(data,count >= 1)
data <- na.omit(data) %>%
# here is the plot code and this is where I need help:
ggplot(data, aes_string(x=var1, y=count, fill=var3))
geom_bar(stat = 'identity',width=1.25,position = position_dodge2(padding=0.25,reverse=FALSE,preserve=c("single")))
geom_text(aes(label=count),vjust=-.5,position=position_dodge2(width=1.25,preserve="single"),size=2.5)
facet_wrap(var1, strip.position="bottom", scales = "free_x", nrow=1)
# I was hoping that the code for strip.text.x would give me the values for var2 (the levels) within each office, but it doesn't.
theme(strip.text.x = element_text(aes(label=data[[var2]]), size=12))
theme(strip.placement = "outside")
} # end function
# here is how I invoke the function, which runs fine except for the axis labels always reflecting only 'office':
myBarChart(data,'office','level','gender',c('office1','office2'),c("A","B","C","D"),'count')
uj5u.com熱心網友回復:
我認為您需要使用levelx 軸、county 軸、facet byoffice和 fill bygender嗎?
像這樣的東西:
data %>%
ggplot(aes(level, count, fill = gender))
geom_col(position = position_dodge2(preserve = "single"))
facet_wrap(~office, strip.position = "bottom")
theme(strip.placement = "outside")
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420806.html
標籤:
