代码之家  ›  专栏  ›  技术社区  ›  Bogaso

使用ggplot构建聚集地块

  •  1
  • Bogaso  · 技术社区  · 2 年前

    我想用我的数据绘制一个带有点的聚类图,如下所示

    library(ggplot2)
    set.seed(1)
    dat1 = data.frame(val = rnorm(20, 0, 1), class1 = rep('a', 20), class2 = rep('X', 20))
    dat2 = data.frame(val = rnorm(20, 0, 1), class1 = rep('b', 20), class2 = rep('X', 20))
    dat3 = data.frame(val = rnorm(20, 0, 1), class1 = rep('a', 20), class2 = rep('Y', 20))
    dat4 = data.frame(val = rnorm(20, 0, 1), class1 = rep('b', 20), class2 = rep('Y', 20))
    dat = rbind(dat1, dat2, dat3, dat4)
    
    ggplot(dat, aes(y = val)) +
      geom_point(aes(x = class2, color = class1))
    

    有了这个,我得到了下面的情节

    enter image description here

    如您所见 class1 在一列中混合 X & Y 。但是,我想保持与 class1 = a class1 = b 它们之间可能有很小的分离空间。

    有什么方法可以使用 ggplot ?

    非常感谢您抽出时间。

    1 回复  |  直到 2 年前
        1
  •  2
  •   Gregor Thomas    2 年前

    我认为现在是使用facets的最佳时机:

    ggplot(dat, aes(x = class1, color = class1, y = val)) +
      geom_point() +
      facet_wrap(vars(class2))
    

    enter image description here

    如果您喜欢原始结构,只想增加一点空间,我们可以使用 position = position_dodge 在指定 group 兼顾两者的美学 class1 class2

    ggplot(dat, aes(y = val, x = class2, color = class1)) +
      geom_point(aes(group = interaction(class1, class2)),
                 position = position_dodge(width = 0.1))
    

    enter image description here