1

I have a basic plot, with a small number of points on. I would like to label the points with a numeric index, and then have the full description of the point in the legend. These is commonly seen on maps, as shown in the following example:

https://www.southampton.ac.uk/assets/imported/transforms/site/location/PDFMap/34014A36B0B34544AE5937646323D1AE/highfield_campus.pdf

However, there seems to be no built-in function within ggplot to add an index. Here is a MWE of the basic concept:

df <- data.frame(x = 6:10, y = 6:10, id = 1:5)
df$label <- paste0("Label", df$id)

library(ggplot)

# Basic plot
ggplot(df, aes(x, y)) +
  geom_point() +
  geom_label(aes(label = id), nudge_x = 0.2)

enter image description here

What I have tried so far is to map the index label to the point by an aesthetic. This way, it creates a legend as follows:

ggplot(df, aes(x, y)) +
  geom_point(aes(fill = label)) +
  geom_label(aes(label = id), nudge_x = 0.2)

enter image description here

This is getting close to a proper index, but ideally, the legend shape would show the numeric count instead of the same shapes. Here is a manual edit of the potential end result:

enter image description here

Does anyone have an idea on how to do this in an elegant way?

There is a previous, unanswered question which is similar to this one: Add numbers to ggplot legend

Nate
  • 10,361
  • 3
  • 33
  • 40
Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • Having searched further, I realise this question is a duplicate. As always, I was just using the wrong search term: https://stackoverflow.com/questions/24801987/numbered-point-labels-plus-a-legend-in-a-scatterplot?rq=1 – Michael Harper Feb 19 '18 at 15:59
  • Although I still feel there should be a better way of doing this, as having an index is quite a common thing to do when making maps! – Michael Harper Feb 19 '18 at 16:00

1 Answers1

0

My best workaround to this problem:

  1. Create a new column within the original dataset which joins the ID and the Label
  2. Use the new column as the aesthetic for the legend
  3. Hide the legend key

This is the code:

df$legend <- paste0(df$id,": ",df$label)

ggplot(df, aes(x, y)) +
  geom_point(aes(fill = legend), alpha = 0) +
  geom_point() +
  geom_label(aes(label = id), nudge_x = 0.2) +
  scale_fill_discrete(name = "Index") +
  theme(legend.key = element_blank(),
        legend.key.width = unit(0, "cm"),
        legend.title.align=0.5)

enter image description here

Still feels a bit messy though so interested to hear other ways of doing this.

Michael Harper
  • 14,721
  • 2
  • 60
  • 84