【问题标题】:How to overlay two plots with different variable treatment?如何用不同的变量处理覆盖两个图?
【发布时间】:2019-08-07 09:26:16
【问题描述】:

我正在尝试用不同的变量处理(来自同一数据集)覆盖两个图: - 第一个带有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))

第一个情节给出:

第二个:

但是如何覆盖它们呢?

【问题讨论】:

  • 您忘记添加Local 对象来创建df
  • 刚刚添加了一行 ;)
  • 查看this 解决方案。

标签: r ggplot2


【解决方案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 不理解轴中的因素。可能有更优雅的解决方案。我还在geom_text_repelaes中插入了label

【讨论】:

    猜你喜欢
    • 2014-01-19
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多