Skip to content

geom_label() can't rotate text & gets descent heights wrong #2785

Closed
@clauswilke

Description

@clauswilke

I think geom_label() could use an overhaul. It has two significant limitations:

  1. Labels can't be rotated (see e.g. Clarify geom_label documentation #2782 and example)
  2. Descent heights are ignored (see example)
library(ggplot2)
library(tibble)

data <- tibble(
  text = c('abc', 'def', 'gjq'),
  angle = c(0, 45, 90),
  x = c(1, 2, 3)
)

ggplot(data, aes(x, label = text, angle = angle)) +
  geom_label(aes(y = 1), label.padding = unit(0, "lines"), size = 10) +
  geom_label(aes(y = 2), size = 10) + xlim(0.5, 3.5) + ylim(0.5, 2.5)

Created on 2018-07-28 by the reprex package (v0.2.0).

I have proof-of-concept code that addresses both issues:

library(gridtext)
library(grid)
library(tibble)

# example with rotated labels, descenders, and padding
label_data <- tibble(
  label = c("Descenders: pgqjy", "This is a label\nwith two lines", "Hello!"),
  x = unit(.4, "npc"),
  y = unit(c(.9, .5, .3), "npc"),
  box_hjust = 0,
  box_vjust = 0.5,
  hjust = 1,
  vjust = 1,
  color = "blue",
  fill = "azure1",
  fontsize = 10,
  fontfamily = "Comic Sans MS",
  angle = c(0, 45, -45),
  padding = list(mar(5, 5, 3, 5)),
  margin = list(mar(5, 5, 5, 5))
)

grid.newpage()
g <- labels_grob(label_data)
grid.draw(g)

# example with no padding and label frames all made the same size
label_data <- tibble(
  label = c("These", "are", "multiple", "labels", "gqpj"),
  x = unit(c(.1, .3, .5, .7, .9), "npc"),
  y = unit(0.5, "npc"),
  box_hjust = 0.5,
  box_vjust = 1,
  hjust = 0.5,
  vjust = 1,
  color = "black",
  angle = 0,
  fontsize = 10,
  margin = list(mar(5, 5, 5, 5))
)
grid.newpage()
g <- labels_grob(label_data, align_frames = TRUE)
grid.draw(g)

Created on 2018-07-28 by the reprex package (v0.2.0).

Fundamentally, the problem is caused by very limited text handling capabilities directly in grid, so it's a fair amount of work to write code that does these things. This raises the issue of whether we should address these problems one-by-one in ggplot2 where they arise or rather write a better text-rendering library and then use that from ggplot2.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions