ggplot2 add a guide for abbreviations

  • A+
Category:Languages

Consider the following toy example

library(tibble) library(ggplot2) library(ggrepel)  df <- tribble(     ~x,  ~y, ~name,            ~initials,     0,   0,  "Hadley Wickam",    "HW",     0,   1,  "Ross Ihaka",       "RI",     1,   0,  "Robert Gentleman", "RG",     1,   1,  "Yihui Xie",        "YX" )  ggplot(df, aes(x, y, label = initials)) +     geom_point() +     geom_text_repel() 

It displays a set of points with labels, where labels are abbreviations of some specific values. What I want to do is to add a guide for the abbreviations similar to a usual point-shape guide, but with abbreviations instead of shapes.

So i want achieve something like this:

ggplot2 add a guide for abbreviations I know there is a solution for the case when all abbreviations are single-letter but unfortunately this is not my case.

Any ideas how this can be done?


Not perfect, but may be a starting point. The point is to assign the initials and name pair to a meaningless aes (in this example fill is used, could be tricky in other situations), and then override the key representation in scale_*().

Some more adjustment may be useful in the theme, particularly this takes up a lot of screen estate:

library(tibble) library(ggplot2) library(ggrepel)  df <- tribble(   ~x,  ~y, ~name,            ~initials,   0,   0,  "Hadley Wickam",    "HW",   0,   1,  "Ross Ihaka",       "RI",   1,   0,  "Robert Gentleman", "RG",   1,   1,  "Yihui Xie",        "YX" )  ggplot(df, aes(x, y,                 label = initials,                 fill = paste(initials, name, sep = '/t-/t'))        ) +   geom_point() +   geom_text_repel() +   scale_fill_discrete('Names', guide = guide_legend(override.aes = list(alpha = 0), title.hjust = .5)) +   theme(legend.key = element_blank()) 

ggplot2 add a guide for abbreviations

Created on 2018-05-10 by the reprex package (v0.2.0).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: