Differece between text and label in ggplots? Error in ggplotly : Too few points to calculate an ellipse

Viewed 57

I don't quite understand the difference between text and label in ggplot2.

For instance:

When I try to convert ggplot2 object to plotly interactive object using label as tooltip, it worked; while I got the Too few points to calculate an ellipse error when using text as tooltip.

Why?


p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species, label = row.names(iris))) +
  geom_point()+
  stat_ellipse(aes(fill = Species), geom = "polygon", level = 0.95, alpha = 0.1, show.legend = F)

ggplotly(p)

p2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species, text = row.names(iris))) +
  geom_point()+
  stat_ellipse(aes(fill = Species), geom = "polygon", level = 0.95, alpha = 0.1, show.legend = F) 

ggplotly(p2)

enter image description here

enter image description here

2 Answers

The issue is most likely the grouping. I have had no look at the ggplot2 source code but I would guess that (in contrast to the label aes) the text attribute (which is no default ggplot2 aesthetic) is used to group the data, i.e. as you use map the rownames on text you end up with groups containing only one row of data. Hence you get a warning about too few points to draw an ellipse.

To prevent that you could or have to explicitly set the group aes in stat_ellipse:

library(plotly)

p2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species, text = row.names(iris))) +
  geom_point()+
  stat_ellipse(aes(fill = Species, group = Species), geom = "polygon", level = 0.95, alpha = 0.1, show.legend = F) 

ggplotly(p2)

Text requires previous label to be shown (as I understand the documentation): Therefore, if one goes to: https://ggplot2.tidyverse.org/reference/geom_text.html; you 'll see that: enter image description here

With that, you see that the real problem is not the creation of the ellipse, but rather how your geom_text() is interpreted in the function. If you write it as following, both ellipse and row.names appear in the graphic:

p2 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species, label = row.names(iris))) +
  geom_point()+
  stat_ellipse(aes(fill = Species), geom = "polygon", level = 0.95, alpha = 0.1, show.legend = F) 

p2+geom_text(check_overlap = T)

The result is the following: enter image description here

Cheers!

Related