我想用我的数据绘制一个带有点的聚类图,如下所示
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))
有了这个,我得到了下面的情节
如您所见 class1 在一列中混合 X & Y 。但是,我想保持与 class1 = a 和 class1 = b 它们之间可能有很小的分离空间。
class1
X & Y
class1 = a
class1 = b
有什么方法可以使用 ggplot ?
ggplot
非常感谢您抽出时间。
我认为现在是使用facets的最佳时机:
ggplot(dat, aes(x = class1, color = class1, y = val)) + geom_point() + facet_wrap(vars(class2))
如果您喜欢原始结构,只想增加一点空间,我们可以使用 position = position_dodge 在指定 group 兼顾两者的美学 class1 和 class2 。
position = position_dodge
group
class2
ggplot(dat, aes(y = val, x = class2, color = class1)) + geom_point(aes(group = interaction(class1, class2)), position = position_dodge(width = 0.1))