0

I was wondering if anyone knew why this is happening. Here is a quick example of the code and screenshots.

library(ggplot2)
iris$randomratio <- iris$Sepal.Length/iris$Sepal.Width
plot_iris <- ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color = Species)) + 
        geom_point() + 
        theme_light() + 
        ggrepel::geom_text_repel(data=subset(iris, randomratio > 2.7), 
                                 aes(Sepal.Length, Sepal.Width, label= Species))
plot_iris
cowplot::plot_grid(plot_iris, plot_iris, label = c('A', 'B'))

Now when I do this in an RMD file I get the points labelled that I want (right) But when I try to do this in the Rstudio notebook output I get the following: enter image description here

NB It doesn't work with ggplot or cowplot. With cowplot it doesn't work in the regular file as well.

Does anyone know how I can fix this?

enter image description here

1 Answers1

0

I see a warning with 'cowplot', but a figure with text labels.

Warning message:
In as_grob.default(plot) :
  Cannot convert object of class character into a grob.

I see no warning with 'patchwork'. You need to be aware that with geom_text() if want to avoid text overlapping the points, instead of sub-setting the data you have to set labels to "". Reducing the size of the labels helps with the repulsion. Collecting identical legends when composing the plot gives also a bit more room. The code below renders well to a HTML notebook under R 4.1.0 and latest versions of the packages.

library(ggplot2)
library(patchwork)

iris$randomratio <- iris$Sepal.Length/iris$Sepal.Width
iris$label <- ifelse(iris$randomratio > 2.7, as.character(iris$Species), "")
plot_iris <- 
  ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color = Species)) + 
  geom_point() + 
  theme_light() + 
  ggrepel::geom_text_repel(aes(label = label), size = 3, min.segment.length = 0)

plot_iris + plot_iris + 
  plot_annotation(tag_levels = 'A') +
  plot_layout(guides = 'collect')

Created on 2021-08-03 by the reprex package (v2.0.0)

Pedro J. Aphalo
  • 5,796
  • 1
  • 22
  • 23