如何在使用多个数据集时为geoms添加图例?

时间:2018-02-01 21:23:07

标签: r ggplot2

我想使用ggplot绘制逻辑回归的结果。我有两个不同的数据框中的预测和数据。最小的工作示例如下所示。

该脚本绘制了逻辑回归以及观察结果。我想将geom_point标记为"观察",将geom_line标记为"回归",将geom_ribbon标记为&# 34; Point Wise CI"。

如何为不同的geoms添加图例?

library(tidyverse)

pic_data<-tibble::tribble(
  ~picloram, ~rep, ~kill, ~total, ~alive,
          0,   1L,    0L,    18L,    18L,
        1.1,   1L,   13L,    24L,    11L,
        2.2,   1L,   28L,    29L,     1L,
        4.5,   1L,   24L,    24L,     0L,
          0,   2L,    0L,    29L,    29L,
        1.1,   2L,   11L,    21L,    10L,
        2.2,   2L,   18L,    24L,     6L,
        4.5,   2L,   31L,    31L,     0L,
          0,   3L,    0L,    28L,    28L,
        1.1,   3L,    9L,    32L,    23L,
        2.2,   3L,   24L,    26L,     2L,
        4.5,   3L,   27L,    27L,     0L
  )

#Inverse logit
inv.logit <- function(x){
  return( 1/(1+exp(-x)) )
}

#Fit a model
glm.model.1 = glm( cbind(kill,alive) ~ picloram, family = binomial(),data = pic_data)

    #Data I will use to plot the regression
gdata = data.frame(picloram = seq(0,4.75,0.01)) 

preds = predict(glm.model.1, newdata = gdata, se.fit = T, type = 'link') %>%
        as.data.frame() %>% 
        transmute(fit = fit,
                  u = fit + qnorm(0.975)*se.fit,
                  l = fit - qnorm(0.975)*se.fit
                  ) %>% 
        map_df(inv.logit)


gdata <- bind_cols(gdata,preds)

#Add the regression first
reg.plot<- ggplot()

reg.plot<-reg.plot +
          geom_line(data = gdata, aes(picloram,fit))+
            geom_ribbon(data = gdata, aes(x = picloram,ymin = l, ymax = u), alpha = 0.25)

#Add plots

reg.plot<-reg.plot +
  geom_point(data = pic_data, aes(picloram, kill/total)) +
  labs(x = 'Concentration of Picloram', y = 'Probability of Killing a Weed')+
  theme_minimal()

 print(reg.plot)

1 个答案:

答案 0 :(得分:1)

默认情况下,ggplot将为每个geom aes()中指定的参数创建图例。所以你可以通过以下内容获得传说:

ggplot(data = gdata,
       aes(x = picloram, y = fit)) +

  geom_line(aes(linetype = "Regression")) +
  geom_ribbon(aes(ymin = l, ymax = u, fill = "Point Wise CI"), alpha = 0.25) +

  geom_point(data = pic_data,
             aes(y = kill / total, shape = "Observations")) +

  labs(x = 'Concentration of Picloram', y = 'Probability of Killing a Weed') +
  theme_minimal() +

  theme(legend.title = element_blank()) +     # hide legend titles
  scale_fill_manual(values = "grey") +        # set ribbon colour as grey
  guides(shape = guide_legend(order = 1),     # specify order of legends
         linetype = guide_legend(order = 2),
         fill = guide_legend(order = 3))

plot