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:
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)
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)
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:
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