R语言 在ggplot中按多因素多水平分组

nhaq1z21  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(176)

我试图为我的数据集创建一个均值和置信区间图。但我需要用两个不同的因素来分组。我进行了四次治疗(对照、原始、低EE 2、高EE 2),并在两个不同的日子(D14和D21)测量了4次治疗中移动的总距离。我也希望每个因素的顺序如上所述。任何帮助将不胜感激,我是非常新的使用R!
下面是我的ggplot的当前代码。..

f <- factor(c("Control", "Virgin", "Low EE2", "High EE2"), levels=c("D14", "D21"))

ggplot(Working_Exp_1_Data_summary, aes(x=Juvenile.Treatment, y=Distance.moved, color=Juvenile.Treatment, fct_relevel(f))) +
  geom_errorbar(aes(ymin=Distance.moved-ci, ymax=Distance.moved+ci), width=0.2) +
  geom_line() +
  geom_point()

我现在的图表。..

jhiyze9q

jhiyze9q1#

正如@alistaire提到的,当你的例子是可复制的时,帮助总是更容易,但我在这里已经尝试过了。
您的数据(大约):

df <- data.frame(
  estimate = c(3200, 3400, 2780, 3790, 3100, 3750, 2900, 4900),
  treatment = c("control", "control", "high ee2", "high ee2", "low ee2", 
                "low ee2", "virgin", "virgin"),
  day = rep(c("d14", "d21"), 4)
)

df$ci_up <- df$estimate + 500
df$ci_lo <- df$estimate - 500

以特定顺序绘制x轴的第一个挑战是对因子进行排序,该因子具有here和其他位置的答案。但要做到这一点,请使用factor()

df$treatment = factor(df$treatment, levels = c("control", "virgin", 
                                               "low ee2", "high ee2"))

现在,绘制数据:

ggplot(df) + 
  geom_point(aes(x = treatment, y = estimate, colour = treatment)) + 
  geom_errorbar(aes(x = treatment, ymin = ci_lo, ymax = ci_up, 
                    colour = treatment), width = 0.2)

但我想你也想根据当天的情况来点菜吧?假设D14是第一个,D21是第二个,我们可以这样排列它们:

df$day = factor(df$day , levels = c("d14", "d21"))

然后绘制:

ggplot(df) + 
  geom_point(aes(x = treatment, y = estimate, colour = treatment, 
                 shape = day), 
             position = position_dodge(width = 0.5)) + 
  geom_errorbar(aes(x = treatment, ymin = ci_lo, ymax = ci_up, 
                    colour = treatment, group = day), width = 0.2,
                position = position_dodge(width = 0.5))

我们不必改变当天的形状,但它可能是有用的。为了保持误差条和点彼此对齐,而不是堆叠在日组上,我们将group = day添加到误差条调用中,并对两者使用position_dodge()。如果你想删除不同的形状,以防止点/误差条在相同的处理中相互堆叠,我们也可以将group = day添加到geom_point()

ggplot(df) + 
  geom_point(aes(x = treatment, y = estimate, colour = treatment, 
                 group = day), 
             position = position_dodge(width = 0.5)) + 
  geom_errorbar(aes(x = treatment, ymin = ci_lo, ymax = ci_up, 
                    colour = treatment, group = day), width = 0.2,
                position = position_dodge(width = 0.5))

相关问题