1
votes

How can I prevent geom_text_repel() to display part of the labels when labels are close to plot boundary. Here is an example with a facet_grid e.g. in chr3 facet the label on the top "ZNF717" is not completely displayed.

enter image description here

example with mtcars with forcing 20 facets and long labels :

mtcars %>% 
rowwise() %>% 
mutate(label="test_label") %>% 
mutate(facet=runif(n = n(),min = 1,max=20)) %>% 
ggplot(aes(x=disp,y=hp,label=label)) + 
geom_text_repel() + 
facet_grid(~facet)

enter image description here

1
Can you simulate some data and share your code to make your example reproducible? - Roman Luštrik
example with mtcars with forcing 20 facets and long labels : mtcars %>% rowwise() %>% mutate(label="test_label") %>% mutate(facet=runif(n = n(),min = 1,max=20)) %>% ggplot(aes(x=disp,y=hp,label=label)) + geom_text_repel() + facet_grid(~facet) - Nicolas Rosewick
Please edit your original question. - Roman Luštrik
Add + coord_cartesian(clip="off") - Marco Sandri
perfect @MarcoSandri ! - Nicolas Rosewick

1 Answers

0
votes

Each panel is self contained and by default plotting is limited to the plotting area. This can be overridden by modifying the default coordinates. With this extreme example, using facet_wrap() with two rows was needed. I also decreased the font size of the labels, and restricted repulsion so that it moves labels only vertically. (Obviously tick labels and panel names would need to be tweaked further in real use.)

library(ggplot2)
library(ggrepel)
library(dplyr)
mtcars %>% 
  rowwise() %>% 
  mutate(label="test_label") %>% 
  mutate(facet=runif(n = n(),min = 1,max=20)) %>% 
  ggplot(aes(x=disp,y=hp,label=label)) + 
  geom_text_repel(direction = "y", hjust = 0.5, size = 2) + 
  facet_wrap(~facet, nrow = 2) +
  coord_cartesian(clip = "off")

The code above answers the question but creates a new problem at least in the mtcars example as geoms work on a panel by panel basis, the repulsion cannot prevent overlap of labels that extend into neighbouring panels. Surprisingly, in addition some unexpected clipping on the left side takes place when saving to bitmap formats but not when saving to PDF (at least within RStudio).

A further option, is to make sure that the labels fit in the available space by using using the angle aesthetic to rotate the labels, or abbreviating the text used for labels.