在geom_point中使用cut时如何在ggplot中添加椭圆

时间:2019-03-30 17:21:15

标签: r ggplot2 vegan

我正在尝试基于geop_point着色将值切成间隔/组,在ggplot中添加椭圆(来自Pkg素食主义者的命令)。我认为使用虹膜数据提供示例会更容易:

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")))

基于此帖子ggplot2 draw individual ellipses but color by group 我尝试修改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"))

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

1 个答案:

答案 0 :(得分:1)

您可以在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创建