r - 在 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。也许循环应该这样做?
我把这个作为图表。显然,我做错了,因为我应该为每个菜单类型设置两个条形图Belief
和learned
比例。
另外,我对 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
解决方案
如果我理解你的问题,这可能就是你所追求的
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
推荐阅读
- rest - Grails 3 REST 安全性获得双重身份验证
- postgresql - 更改查询需要很长时间
- sql - 如何修复 ORA-01008:并非所有变量都绑定在 asp.net 中
- c# - 使用 C#(尤其是循环时间码)检查 ogg 文件属性 - 可能吗?
- c# - Paypal TLS1.2 / Http1.1 升级 - PayPal 支付标准的 HTML 表单基础
- tslint - tslint 使用 --project 时不排除 tsconfig.json 中的文件
- loops - 如何优雅地将变量传递给命令
- java - 继承设计模式的不变性
- sql - SQL 多对多过滤器只针对特定的数据组合
- python - Django:模型每个条目的表单