【问题标题】:ggplot jitter geom_errorbar?ggplot jitter geom_errorbar?
【发布时间】:2019-09-12 23:26:33
【问题描述】:

我的数据如下所示:

df1 <-
  structure(
    list(
      y = c(-0.19, 0.3,-0.05, 0.15,-0.05, 0.15),
      lb = c(-0.61,
             0.1,-0.19,-0.06,-0.19,-0.06),
      ub = c(0.22, 0.51, 0.09, 0.36,
             0.09, 0.36),
      x = structure(
        c(1L, 2L, 1L, 2L, 1L, 2L),
        .Label = c("X1",
                   "X2"),
        class = "factor"
      ),
      Group = c("A", "A", "B", "B", "C",
                "C")
    ),
    .Names = c("y", "lb", "ub", "x", "Group"),
    row.names = c(NA,-6L),
    class = "data.frame"
  )

我想使用ggplot2 绘制由group 着色的点x,y,并带有误差线lb, ub。因为x 是离散的,我想jitter 所以点和条不重叠。现在,我可以jitter 点而不是线。另外,我希望点的顺序是 A,B,C

ggplot(data = df1, aes(x, y, color = Group)) + geom_point(size = 4, position = "jitter") +
  geom_errorbar(
    aes(ymin = lb, ymax = ub),
    width = 0.1,
    linetype = "dotted"
  ) +
  geom_hline(aes(yintercept = 0), linetype = "dashed") + theme_bw()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用position_dodge 来实现所需的顺序和在点的位置绘制的误差线

    ggplot(data = df1, aes(x, y, color = Group)) +
        geom_point(size = 4, position=position_dodge(width=0.5)) +
        geom_errorbar(
            aes(ymin = lb, ymax = ub),
            width = 0.1,
            linetype = "dotted",
            position=position_dodge(width=0.5)) +
        geom_hline(aes(yintercept = 0), linetype = "dashed") + 
        theme_bw()
    

    【讨论】:

    • 这是一个很好的答案,但是如果每个 x 轴类别中有多个点怎么办? position_width 将所有点放在一条垂直线上,以便误差条在类别内重叠。有没有办法在类别内实现进一步的抖动,并且误差线仍然与点对齐?
    • @EcologyTom 你可以定义一个新的因素来考虑每个类别的点数吗?例如,如果您在 A 类中有 2 分,则您的因子水平将是 A1、A2、B、C .. 我认为没有一种方法可以像您描述的那样结合闪避和抖动
    • 这似乎是一个很好的解决方法。我最终确实找到了提供解决方案的this answer。但你的建议会更直接,特别是如果没有太多的点。谢谢!
    【解决方案2】:

    如果你想要抖动,我喜欢这样:

    ggplot(data = df1, aes(x, y, color = Group)) +
        geom_pointrange(aes(ymin = lb, ymax = ub), 
                        position=position_jitter(width=0.5), 
                        linetype='dotted') +
        theme_bw()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2021-07-23
      • 2015-10-28
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多