R -创建具有精确限制的分组条形图的问题

z9ju0rcb  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(178)

我试图创建一个分组条形图,共有4条(没有支持的男性的愿望,没有支持的女性的愿望,得到支持的男性的愿望,得到支持的女性的愿望),加上误差条。变量“wish”是在1-5的范围内测量的,因此我试图相应地设置限制,但这导致图表中只显示误差条,而不显示“主”条,并出现以下错误消息:
警告消息:删除了包含缺失值(geom_bar())的4行。

ggplot(wish_c, aes(x=factor(esnonrom_t,
                            levels = c("0", "1"),
                            labels = c("Received no support (n = 89)", "Received support (n=795)")), 
                   y=wish_for_partner_t1, 
                   fill=factor(sex_gen, 
                               levels = c("0", "1"), 
                               labels=c("Men (n=427)", "Women(n=457)")))) +
  geom_bar(position=position_dodge(), stat="identity")  +
  geom_errorbar(aes(ymin=wish_t1-se, ymax=wish_t1+se),
                width=.2,                    # Width of the error bars
                position=position_dodge(.9)) +
  scale_y_continuous("Wish (1-5)", limits=c(1,5), breaks=seq(1,5, by =1)) +
  theme_classic() +
  scale_fill_brewer(palette = "Greys") +
  labs(x = "Emotional support received 
       beyond the romantic relationship",
       fill = "Gender",
       title = "Wish by gender and emotional support")
yacmzcpb

yacmzcpb1#

一种方法是使用stat_summary()
我创建了一个示例数据集:

library(dplyr)
library(ggplot2)
library(tidyr)

set.seed(123)  

# example dataset
df <- data.frame(
  group = rep(c("Men - No Support", "Women - No Support", "Men - Support", "Women - Support"), each = 25),
  wish = round(runif(100, min = 1, max = 5), 1), 
  group2 = 
)

df %>% 
  separate(group, into = c("sex", "Support"), sep = " - ") %>% 
  ggplot(., aes(x = sex, wish, fill = Support))+
  stat_summary(fun= "mean", geom="col", position = "dodge")+
  stat_summary(fun.data = "mean_se", geom = "errorbar", width = 0.2, 
               position = position_dodge(width = 0.9))+
  theme_classic()

相关问题