removing confidance ellipses for some groups when using stat_ellipse ggplot2

Viewed 923

You have a scatter plot with several groups (for example 10). You draw the 95% confidance ellipses for the groups.

Problem: you don't need to see the confidance ellipses of all groups (because is not necessary or because some of them have few points, resulting in huge ellipses)

Question: how do you remove confidance ellipses of determined groups while keepiing the point on the scatter plot?

Example: In this code you wish to remove the confidance ellipse of versicolor, but keeping the points with their colour and keeping the other ellipses

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point() +
  stat_ellipse(aes(color = Species)) +
  theme(legend.position = "bottom")    

Example

2 Answers

The legend in Z.lin's answer would not be accurate as versicolor still has a line going through the shape even though no ellipse were plotted. We can bypass this by specifing aes(linetype = Species) and the scale_linetype_manual.

library(dplyr, ggplot2)

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point(aes(shape = Species)) +
  stat_ellipse(aes(linetype = Species)) +
  scale_linetype_manual(values = c(1,0,1)) +
  theme(legend.position = "bottom")

[No Legend here :)]

You can filter the data passed to the stat_ellipse layer to include only groups for which you want ellipses:

library(dplyr)

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point() +
  stat_ellipse(data = . %>% filter(Species != "versicolor"),
               aes(color = Species)) +
  theme(legend.position = "bottom")   

result

Related