首页 > 解决方案 > 在 R 中并排创建多组直方图

问题描述

我正在尝试在 R中复制这些研究的直方图。

我有一个来自这项研究的庞大数据集,所以我认为我无法将其粘贴到这里,但这里有一个简短的版本:

menutype menuselection belieflearn learned
5              1           0          0
11             1           1          0
2              3           0          0
2              3           0          0
2              1           0          0
2              1           0          0
10             1           0          0
12             3           0          0
8              3           0          1
12             3           0          0

想法如下:首先,我只选择变量“ menuselection == 3”所在的变量。然后,对于这些变量,对于menutype图表上分别对应于“GUILT”、“SSB0”... belieflearn == 1) 以及玩家选择选项 1 时的频率(如果learned == 1)。

我认为factor()需要在这里使用,但我不太了解如何使用。我已经关注了这个线程并且我已经尝试过这个:

df2 <- data.frame(
  menutype =  factor(df$menutype, labels = c("GUILT", "SSB0", "SSB1", "FLEX0", "FLEX1", "STD", "FLEX01", "test1","test2", "test3", "test4", "test5" )),
  Belief = factor(df$belieflearn, labels= c("Believe not learn", "Believe Learn")),
  Choice = factor(df$learned, labels= c("Not learn", "Learn"))
)


df3 <- df2 %>%
  count(Belief, menutype) %>%
  group_by(Belief) %>% 
  mutate(prop = n / sum(n))


ggplot(data = df3, aes(menutype, prop , fill = Belief)) +  
  geom_bar(stat = "identity", position = "dodge")

哪个有效,但我想排除 menutype>7 的值(我放了 test1,test2 以使其factor()正常工作,但最佳情况下,我想摆脱它们)。我尝试了 exclude() 但没有成功。

我也没有指定 menuselection == 3。也许循环应该这样做?

我把这个作为图表。显然,我做错了,因为我应该为每个菜单类型设置两个条形图Belieflearned比例。

另外,我对 R(和 StackOverflow)还很陌生,所以如果我应该在这个线程中添加一些东西,请告诉我!

谢谢您的帮助。

编辑:我在原始研究中找到了用于生成图形的 Stata 代码,所以这里是:

  graph bar (mean) belieflearn learned if menuselection==3, over(menutype, relabel(1 "{it:{stSerif:GUILT}}" 2 "{it:{stSerif:SSB_{subscript:0}}}" 3 "{it:{stSerif:SSB_{subscript:1}}}" 4 "{it:{stSerif:FLEX_{subscript:0}}}" 5 "{it:{stSerif:FLEX_{subscript:1}}}" 6 "{it:{stSerif:STD_{subscript:0}}}" 7 "{it:{stSerif:FLEX_{subscript:0v1}}}" ))  ///
ytitle("fraction of subjects") yvaroptions(relabel(1 "expected Option 1 (reading)" 2 "chose Option 1 (reading)")) title("classification based on rank ordering") ///
bar(1, bcolor(navy)) bar(2, bcolor(red*0.4) lcolor(red*0.9))  ///
ylab(0(0.2)1, nogrid) blabel(bar, position(outside) format(%9.2f)) graphregion(color(white)) saving(f1, replace) nodraw

标签: rhistogram

解决方案


如果我理解你的问题,这可能就是你所追求的

ggplot(data = df3, 
aes(interaction(menutype,Belief),  #get combination of groups
prop , fill = Belief) + 
geom_bar(stat = "identity", position = "dodge")+
scale_x_discrete(labels = levels(df3$menutype)) # adds clean label to x

推荐阅读