出现边距时facet_grid中的颜色和形状美观

时间:2018-08-19 23:21:41

标签: r ggplot2 margins facet-grid aesthetics

请考虑以下数据:

n <- 1000  
data <- data.frame(id = 1:n,
                 a = sample(c("a1", "a2"), n, replace = T),
                 b = sample(c("b1", "b2", "b3"), n, replace = T),
                 x = rnorm(n),
                 y = rnorm(n))

我正在为 a b 每个带有边距的组合在网格中创建散点图。

library(ggplot2)
  ggplot(data, aes(x = x, y = y)) +
  geom_jitter(aes(color = b, shape = a)) +
  facet_grid(a ~ b, margins = T)

这为称为(全部)的两个因素创建了一个额外的水平,对我而言这毫无意义。

我希望获得即使在边际图上也可以通过颜色和形状区分点的效果。

1 个答案:

答案 0 :(得分:0)

一种解决方案是创建一个变量以独立进行着色和刻面:

n <- 1000  
data <- data.frame(id = 1:n,
                   a = sample(c("a1", "a2"), n, replace = T),
                   b = sample(c("b1", "b2", "b3"), n, replace = T),
                   x = rnorm(n),
                   y = rnorm(n)) %>%
  mutate(a_ = factor(a),
         b_ = factor(b))

library(ggplot2)
ggplot(data, aes(x = x, y = y)) +
  geom_jitter(aes(color = b, shape = a)) +
  facet_grid(a_ ~ b_, margins = T)