我有以下資料集(在檔案emp1.txt中),我想根據年齡范圍畫一個分組條形圖,同時我想為每個組的男性和女性做疊加選項。
Count Male Female Emp_group
38 10 28 作業人員
38 20 18 老師
33 15 18 教師
34 17 17 教師
41 35 6 作業人員
45 25 20 教師
35 17 18 員工
39 30 9 職員
39 9 30 教師
44 22 22 員工
42 20 22 教師
這是我所嘗試的,但無法弄清堆疊部分。我將感謝任何幫助。紅條和綠條都應該分為兩部分,分別為Male和Female。我還想在圖例中為Male和Female添加顏色說明。
data <- read.csv(/span>"emp1. txt", sep = " " , 頭= TRUE)
df1<-tibble(data)
df1< - mutate(df1,emp_class = cut(Count, 打破= c(0。 30, 40, 50。 60, 100),
標簽 = c('(0-30)'。 '(31-40)'。 '(41-50)', '(51-60)'。 '(61-100)')))
df1 <- df1 %>%
group_by(Emp_group) %>%
add_count()
df1 < - mutate(df1, x_axis = paste(Emp_group。 n, sep = "
"))
my_ggp <- ggplot(df1, aes(x= as. factor(x_axis), fill=as. factor(emp_class))
geom_bar(aes( y=.count. ./tapply(.count., .x. ,sum)[/span>...x。 ]*100)。 位置="dodge") ="dodge") ylab('% Employes') xlab("") 實驗室(fill = "Count group")
df1
my_ggp 主題(text = element_text(size = 20))
uj5u.com熱心網友回復:
你需要position = "stack"而不是"dodge"。
我對你的代碼進行了輕微的重組:
library(ggplot2)
library(dplyr)
資料 %>%
mutate(emp_class = cut(Count,)
休息= c(0, 30, 40。 50, 60。 100),
標簽 = c('(0-30)'。 '(31-40)'。 '(41-50)', '(51-60)'。 '(61-100)')
)
) %>%
pivot_longer(c(Male, 女),
names_to = "MF") %>%
group_by(Emp_group,MF) %>;%
add_count() %>%
mutate(x_axis = as. factor(paste(Emp_group。 n,sep = "
")) %>%
ggplot(aes(x = x_axis, fill= as. factor(emp_class))
geom_bar(aes(y = value),>
position = "fill",
stat = "identity")
labs(x = ""。 y = "% Employes"。 填充= "年齡組")
主題(文本= element_text(大小= 20))
facet_wrap(~MF)
scale_y_continuous(labels =scales:: percent_format())
這將回傳
資料
structure(list(Count = c(38。 38, 33。 34, 41, 45, 35, 39, 39, 39
44, 42)。 男= c(10。 20, 15, 17。 35, 25。 17, 30。 9, 22。 20),
女= c(28。 18。 18, 17。 6,/span> 20。 18,/span> 9, 30, 22。 22)。 Emp_group = c("Staff",)
"教師", "教師",。 "作業人員", "教師"。 "作業人員", "作業人員",
"作業人員", "教師", "作業人員"。 "教師"))。 class = c("spec_tbl_df"/span>。
"tbl_df", "tbl", "資料。 ),行。 names = c(NA。 -11L)。 spec = structure(list()
cols = list(Count =結構(list()。 class = c("collector_double"。
"collector"))。 男=結構(串列()。 class = c("collector_double"。
"collector"))。 女=結構(list()/span>。 class = c("collector_double"。
"collector"))。 Emp_group =結構(list()。 class = c("collector_character"/span>。
"collector")))。 默認=結構(list()/span>。 class = c("collector_guess"。
"collector"))。 skip = 1L)。 class = "col_spec"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318959.html
標籤:
上一篇:波譜圖:標記一個離群點


