Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ggrepel with single plot point/adding line between label and point

Ok so I have a data set with 2 variables X and Y, and an ID variable. I've created a full plot using this code:

ggplot(data = X_Y) + 
  geom_point(mapping = aes(x = X, y = Y))+
  geom_text_repel(mapping = aes(x = X, y = Y, label = ID))+
  xlim(0,100)+
  ylim(0,100)

This produces a plot like this: enter image description here

I now wish to create a number of separate plots only showing a single data point at a time with their label.

Now I can use just geom_label without repel and nudge the label to get this: enter image description here

While this plot is ok, I was wondering if there was any way to keep the lines connecting labels to points like how ggrepel does...

EDIT

From the first suggestion, when I try use repel with only one case selected I get the following plot:

ggplot(data = X_Y) + 
  geom_point(aes(x = X[4], y = Y[4]))+
  geom_label_repel(aes(x = X[4], y = Y[4]), 
                   label = "You are here",
                   min.segment.length = unit(0, 'lines'),
                   nudge_y = 6)+
  labs(x = "X",y = "Y",title = "mytitle")+
  scale_x_continuous(limits = c(0, 100)) +
  scale_y_continuous(limits = c(0, 100))

enter image description here

RESOLVED

Figured it out! I need to specify my data in ggplot() to only be the X and Y variables and limit to the row of interest.

Like this:

ggplot(data = X_Y[4,c(3,4)) + 
  geom_point(aes(x = X, y = Y))+
  geom_label_repel(aes(x = X, y = Y), 
                   label = "You are here",
                   min.segment.length = unit(0, 'lines'),
                   nudge_y = 6)+
  labs(x = "X",y = "Y",title = "mytitle")+
  scale_x_continuous(limits = c(0, 100)) +
  scale_y_continuous(limits = c(0, 100))
like image 877
Gerard Avatar asked Apr 20 '17 12:04

Gerard


1 Answers

You can of course still use geom_label_repel, even with a single point. To be sure a segment is drawn adjust the min.segment.length arg. This arg sets the minimum distance from the point to the label to draw a segment, setting it to unit(0, 'lines') ensures every segment is drawn:


library(ggplot2)
library(ggrepel)

ggplot(data.frame(x = 2, y = 3)) +
    geom_point(aes(x, y)) +
    geom_label_repel(aes(x, y), 
                     label = 'You are here', 
                     min.segment.length = unit(0, 'lines'), 
                     nudge_y = .2) +
    scale_x_continuous(limits = c(0, 3)) +
    scale_y_continuous(limits = c(0, 4))

like image 102
GGamba Avatar answered Oct 22 '22 13:10

GGamba