gpt4 book ai didi

r - 使用 `gpplot2` 使用多个因子变量复制 `sciplot`

转载 作者:行者123 更新时间:2023-12-02 05:07:02 26 4
gpt4 key购买 nike

我非常喜欢使用 sciplot 来获取实验数据,因为我不必手动计算误差线。过去,我用它来对两个因子变量进行分组,例如:

plot1<-bargraph.CI(
df$factor1, #categorical factor for the x-axis
df$y, #numerical DV for the y-axis
df$factor2 #grouping factor
)

但是,我现在需要对三个因子变量进行分组。 sciplot 文档表明这在 sciplot.

中是不可能的

那么,现在是问问题的必要时间了……我究竟该如何使用 ggplot2 来做到这一点?具体来说,是否有一种简约的方法来生成带有超过 3 个因子变量的误差条的图形?我在网上四处搜寻,但在寻找优雅的解决方案时不断出现问题。

示例数据如下:

factor1          factor2             factor3     y
More expensive Least important Blue 1
Less expensive Most important Blue 0
Same cost Least important Red 1
More expensive Least important Red 0
Less expensive Most important Red 1
Same cost Least important Blue 1
More expensive Least important Red 1
Less expensive Least important Blue 0
Same cost Most important Red 1

最佳答案

您可以通过两次调用 stat_summary 来复制(在一定程度上)sciplot

您可以将两个因素级别合并为一个interaction(使用interaction)或使用faceting。

我将使用 ToothGrowth,它包含在带有基础 R 的数据集包中。

# add third factor
ToothGrowth$F3 <- letters[1:2]
# coerce dose to a factor
ToothGrowth$dose <- factor(ToothGrowth$dose, levels = c(0.5,1,2))

# interaction on the x axis
ggplot(ToothGrowth, aes(y = len, x = interaction(supp, F3))) +
stat_summary(fun.y = 'mean', fun.ymin = function(x) 0, geom = 'bar',
aes(fill =dose), position = 'dodge') +
stat_summary(fun.ymin = function(x) mean(x) - sd(x),
fun.ymax = function(x) mean(x) + sd(x), position ='dodge',
geom = 'errorbar', aes(group = dose))

enter image description here

# facetting on the third factor
ggplot(ToothGrowth, aes(y = len, x = supp )) +
stat_summary(fun.y = 'mean', fun.ymin = function(x) 0, geom = 'bar',
aes(fill =dose), position = 'dodge') +
stat_summary(fun.ymin = function(x) mean(x) - sd(x),
fun.ymax = function(x) mean(x) + sd(x), position ='dodge',
geom = 'errorbar', aes(group = dose))+
facet_wrap(~F3)

enter image description here

ggplot(ToothGrowth, aes(y = len, x = supp)) + 
stat_summary(fun.y = 'mean', fun.ymin = function(x) 0,
geom = 'bar', aes(fill =interaction(dose, F3)),
position = 'dodge') +
stat_summary(fun.ymin = function(x) mean(x) - sd(x),
fun.ymax = function(x) mean(x) + sd(x),
position ='dodge', geom = 'errorbar',
aes(fill =interaction(dose, F3)))

enter image description here

关于r - 使用 `gpplot2` 使用多个因子变量复制 `sciplot`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16138206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com