Home > other >  Differece between text and label in ggplots? Error in ggplotly : Too few points to calculate an elli
Differece between text and label in ggplots? Error in ggplotly : Too few points to calculate an elli

Time:04-17

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

CodePudding user response:

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)

CodePudding user response:

Text requires previous label to be shown (as I understand the documentation): Therefore, if one goes to: 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