如何用不同的变量处理覆盖两个地块?

时间:2019-08-07 09:26:16

标签: r ggplot2

我正在尝试用不同的变量处理重叠两个图(来自同一数据集): -第一个带有mutatereorder的(用来制作geom_boxplot + geom_jitter); -第二个带有group_bysummarize(用于制作geom_line)。两者都必须覆盖。

当我尝试以下代码时,给出此错误:Aesthetics must be either length 1 or the same as the data (4): label

Local <- c("A", "B", "C", "D", "A", "B", "C", "D")
Case <- c("QQ", "DD", "GG", "PP", "QQ", "DD", "GG", "PP")
Div <- c(2, 4, 5, 1, 3, 5, 6, 7)
dat <- data.frame(Local, Case, Div)

p1 <- dat %>%
  mutate(Loc = reorder(Local, Div, FUN = median)) %>%
  ggplot(aes(Loc, Div, label = Case)) +
  geom_boxplot(outlier.size = -1) +
  geom_jitter(width = 0.1, alpha = 1, aes(color = Case, size = Div)) +
  geom_text_repel()

dat %>%
  group_by(Local) %>% 
  summarise(Div = mean(Div)) %>%
  mutate(Loc = reorder(Local, Div, FUN = median)) %>%
  ggplot(aes(Loc, Div, group = 1)) +
  geom_line()

p1 + geom_line (data = dat %>%
              group_by(Local) %>% 
              summarise(Div = mean(Div)) %>%
              mutate(Loc = reorder(Local, Div, FUN = median)), aes(Loc, Div, group = 1))

第一个情节给出:

Plot1

第二个:

Plot1

但是如何覆盖它们呢?

1 个答案:

答案 0 :(得分:1)

datBox <- dat %>%
  mutate(Loc = reorder(Local, Div, FUN = median)) 
datLine <- dat %>%
  group_by(Local) %>% 
  summarise(Div = mean(Div)) %>%
  mutate(Loc = reorder(Local, Div, FUN = median)) %>% 
  mutate(LocNum = recode(Loc, A = "1", D="2", B="3", C="4"))


ggplot(data = datBox, aes(Loc, Div)) +
geom_boxplot(outlier.size = -1) +
  geom_jitter(width = 0.1, alpha = 1, aes(color = Case, size = Div)) +
  geom_text_repel(aes(label = Case)) + 
  geom_line(data =datLine, aes(as.numeric(LocNum),Div))

我用一个与Loc因子的顺序相对应的数值作为辅助轴。 geom_line不喜欢轴上的因子。有可能是更优雅的解决方案。我也将label插入了geom_text_repel aes