Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 add a guide for abbreviations

Tags:

r

ggplot2

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:

enter image description here 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?

like image 628
Iaroslav Domin Avatar asked May 10 '18 13:05

Iaroslav Domin


1 Answers

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

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

like image 108
GGamba Avatar answered Oct 04 '22 09:10

GGamba