为各种stat_ellipse添加图例

时间:2019-03-29 17:31:25

标签: r ggplot2

我有一个带有各种数据椭圆(stat_ellipse)的图,因此我改变了alpha电平。如何在图上添加图例以对应各种椭圆(带有颜色和Alpha级别)?

 library(tidyverse)
 library(RColorBrewer)

colors <- brewer.pal(n = 8, name = "Blues")
ggplot(faithful, aes(waiting, eruptions)) +
  geom_point(alpha=0.1, color='navy') +
   stat_ellipse(level=0.1, color=colors[1], size=1.1) +
   stat_ellipse(level=0.2, color=colors[2], size=1.1) +
   stat_ellipse(level=0.3, color=colors[3], size=1.1) +
   stat_ellipse(level=0.4, color=colors[4], size=1.1) +
   stat_ellipse(level=0.5, color=colors[5], size=1.1) +
   stat_ellipse(level=0.6, color=colors[6], size=1.1) +
   stat_ellipse(level=0.7, color=colors[7], size=1.1) +
   stat_ellipse(level=0.8, color=colors[8], size=1.1)  +
   stat_ellipse(level=0.9, color='navy', size=1.1)

1 个答案:

答案 0 :(得分:0)

我不知道stat_ellipse是否可行。这是一个解决方案。它包括使用car包计算椭圆,然后使用geom_path

library(car)
levels <- seq(0.1, 0.9, by = 0.2)
ell <- dataEllipse(faithful$waiting, faithful$eruptions, draw = FALSE, 
                   levels = levels, segments = 200)

library(purrr)
paths_list <- imap(ell, function(mat, level){
  cbind(mat, level=as.numeric(level))
})
paths <- as.data.frame(do.call(rbind, paths_list))
paths$level <- as.factor(paths$level)

ggplot(faithful, aes(waiting, eruptions)) +
  geom_point(alpha=0.5, color='navy') +
  geom_path(aes(x=x, y=y, group=level, color=level), data=paths, size = 2)

enter image description here