在 geom_point 中使用 cut 时如何在 ggplot 中添加省略号

how to add ellipses in ggplot when using cut in geom_point

我正在尝试根据使用 geom_point 切割成 intervals/groups 的值在 ggplot(来自 Pkg vegan 中的排序)中添加省略号以进行着色。我认为如果我提供一个使用虹膜数据的例子会更容易:

data("iris")
T <- metaMDS(iris[1:4]) #perform an ordination with the package vegan
ScIris <- as.data.frame(scores(T)) #extract the values for plotting
RandomNumbers <- runif(150, 1, 100) #generate metaData used for colors
ScIris$test_stat <- RandomNumbers

下面的代码生成的绘图具有正确着色的点,但只在所有点周围添加一个椭圆。

ggplot(ScIris, aes(NMDS1, NMDS2)) +
geom_point(aes(colour = cut(test_stat, c(0, 25, 50, 75, 85,95, 99, 100))),
             size = 5) +
   stat_ellipse() +
  scale_color_manual(name = "proportions",
                     values = c("(0,25]" = "black",
                                "(25,50]" = "dark green",
                                  "(50,75]" = "green",
                                  "(75,85]" = "yellow",
                                   "(85,95]" = "orange",
                                    "(95,99]" = "purple",
                                    "(99,100]" = "blue",
                     labels = c("0", "25", "50", "75", "85", "95","<100")))

基于此 post 我尝试修改 stat_ellipse 参数,但没有任何内容可以正确绘制。

stat_ellipse(aes(x=NMDS1, y=NMDS2, colour = cut(test_stat, c(0, 25, 50, 75, 85,95, 99, 100), group=cut(test_stat, c(0, 25, 50, 75, 85,95, 99, 100)),type = "norm"))

如何为每个 grouping/cut 组添加椭圆?因此,黑色椭圆表示 0-25 之间的点,蓝色椭圆表示 99-100 等。ggplot 很棒,但学习曲线很陡。

您可以在 geom_point 中即时创建组(cut 就是这样做的)但是您需要再次使用这些组来处理椭圆及其颜色。所以最好先定义组。

library("tidyverse")
library("vegan")

data("iris")
T <- metaMDS(iris[1:4]) #perform an ordination with the package vegan

# For reproducibility
set.seed(1234)

ScIris <- as.data.frame(scores(T)) %>%
  mutate(test_stat = runif(150, 1, 100)) %>%
  mutate(group = cut(test_stat, c(0, 25, 50, 75, 85, 95, 99, 100)))

ggplot(ScIris, aes(NMDS1, NMDS2)) +
  geom_point(aes(colour = group), size = 5) +
  stat_ellipse(aes(color = group, group = group)) +
  scale_color_manual(name = "proportions",
                     values = c("(0,25]" = "black",
                                "(25,50]" = "dark green",
                                "(50,75]" = "green",
                                "(75,85]" = "yellow",
                                "(85,95]" = "orange",
                                "(95,99]" = "purple",
                                "(99,100]" = "blue",
                                labels = c("0", "25", "50", "75", "85", "95","<100")))
#> Too few points to calculate an ellipse
#> Warning: Removed 1 rows containing missing values (geom_path).

reprex package (v0.2.1)

于 2019-03-31 创建