问题描述
我有一个包含五(5)列数据的数据框。第一个是主要分组(类别1或类别2),其他列变量V1至v4是特征及其存在(1 =否和2 =是)。我想绘制每个类别以及每个变量V1至V4的特征计数的条形图...最好不要更改周围的数据框,但是如果需要的话可以。我想从中实现的数据脚本和图表如下。所有变量都是因素。目的是查看哪些特征在Cat 1和Cat 2中占主导地位。欢迎任何方向或链接。
cat = as.factor(c(1,1,2,2))
v1 = as.factor(c(1,1))
v2 = as.factor(c(1,1))
v3 = as.factor(c(1,2))
v4 = as.factor(c(1,1))
df = data.frame(cat,v1,v2,v3,v4)
解决方法
library(tidyverse)
facet_labeller <- function(string,prefix = "Cat = ") paste0(prefix,string)
df %>%
pivot_longer(c(v1:v4)) %>%
mutate(value = fct_recode(value,c(no = "1"),c(yes = "2"))) %>%
group_by(cat,name,value) %>%
add_count() %>%
ggplot(aes(name,n,group = value,fill = value)) +
geom_bar(stat = "identity",position = position_dodge(.9),show.legend = F) +
geom_text(aes(label = value,y = -.1),position = position_dodge(.9)) +
facet_wrap(~cat,strip.position = "bottom",labeller = as_labeller(facet_labeller)) +
theme(panel.background = element_blank(),panel.border = element_rect(fill = NA))
,
一种方法是重塑数据,在每个类别和图表中将“是”和“否”计数:
library(tidyverse)
cust_labeller <- function(x) paste0("Cat = ",x)
df %>%
pivot_longer(cols = -cat) %>%
count(cat,value) %>%
mutate(value = recode(value,`1` = 'no',`2` = 'yes')) %>%
ggplot() + aes(name,fill = value) +
geom_col(position = 'dodge') +
scale_fill_manual(values = c('blue','red')) +
facet_wrap(.~cat,labeller = as_labeller(cust_labeller),strip.position="bottom")