【问题标题】:Change color of points within group while keeping jitter using ggplot使用 ggplot 在保持抖动的同时更改组内点的颜色
【发布时间】:2020-12-15 09:26:10
【问题描述】:

我正在使用 R 和 ggplot 生成带有单个数据点叠加的箱线图。 x 轴上有两个主要组(sampleData 中的 var1)。第二组还有一个小分区(var2),我想用点填充来表示。我已经使用 ggnewscale 包中的 new_scale_fill 函数成功完成了这项工作。

但是,当我这样做时,它似乎会改变抖动,使得次要分割点 (var2) 在箱线图的左侧和右侧全部组合在一起。有没有办法避免这种情况并将所有点随机分组在 var1 组中?

示例数据和图形输出如下。

sampleData <- data.frame(numVal = c(rnorm(100)),
                         var1 = c(rep(c("x1", "x2"), each = 50)),
                         var2 = c(rep(c("x1","x2","x3"), times = c(50, 30, 20))),
                         var3 = c(rep(c("t1", "t2", "t3", "t4"), 25)))

ggplot(sampleData, aes(x = var1, y = numVal)) +
  geom_boxplot(aes(fill = var1), alpha = 0.7) +
  scale_fill_manual(values = c("red", "blue")) +
  new_scale_fill() +
  geom_point(aes(fill = var2), shape = 21,
             position = position_jitterdodge()) +
  scale_fill_manual(values = c("red", "blue", "white")) 
  theme(legend.position = "none")


【问题讨论】:

    标签: r ggplot2 data-visualization jitter


    【解决方案1】:

    您可以尝试position_jitterdodge 函数内部的参数dodge.width。将dodge.width 设置为零将混合蓝色和白色点。

    ggplot(sampleData, aes(x = var1, y = numVal)) +
      geom_boxplot(aes(fill = var1), alpha = 0.7) +
      scale_fill_manual(values = c("red", "blue")) +
      new_scale_fill() +
      geom_point(aes(fill = var2), shape = 21,
                 position = position_jitterdodge(dodge.width = 0)) +
      scale_fill_manual(values = c("red", "blue", "white")) 
    
    

    编辑:第三个变量

    如果您在 x 轴上放置第三个变量,您可能需要控制轴和填充参数之间的交互。这是一个想法:

    ggplot(sampleData, aes(x = interaction(var1,var3), y = numVal)) +
      geom_boxplot(aes(fill = var1), alpha = 0.7) +
      scale_fill_manual(values = c("red", "blue")) +
      new_scale_fill() +
      geom_point(aes(fill = interaction(var1,var2)), shape = 21,
                 position = position_jitterdodge(dodge.width = 0)) +
      scale_fill_manual(values = c("red", "blue", "white"),
                        labels = c("x1", "x2", "x3"),
                        name = "var2") +
      labs(x = "var3") +
      facet_grid(.~ var3, scale = "free_x", switch = "x") +
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank(),
            panel.spacing.x = unit(0, "lines"),
            strip.background = element_rect(fill = "transparent"))
    

    【讨论】:

    • 这是一个很好的答案,谢谢。虽然它在这个实例中有效,但它在更复杂的实例中不起作用,例如,如果您用新的 var3 替换 x 轴变量,那么您在 x 轴上有两个变量的多个分组。
    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    相关资源
    最近更新 更多