Skip to content

Suggestion: rel-class can inherit value from unit-class theme elements #3951

@teunbrand

Description

@teunbrand

I know rel objects are not really supported as theme elements on their own, but since the size argument in element_line/rect/text() can take a rel object and inherit the (modified) value from the parent, it doesn't seem like too far a stretch to have child rel theme elements.

Suppose you'd like your legend keys to be half as tall as usual, it would be neat if you could do the following:

library(ggplot2)

ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(colour = Species)) +
  theme(legend.key.height = rel(0.5))
#> Error: Theme element `legend.key.height` must be an `unit` object.

Created on 2020-04-18 by the reprex package (v0.3.0)

I think it would require changes at these locations.

  • This check would have to allow rel classes for unit elements

ggplot2/R/theme.r

Lines 530 to 533 in 7e6d125

if (!is.null(el_out) &&
!inherits(el_out, element_tree[[element]]$class)) {
abort(glue("{element} should have class {ggplot_global$element_tree[[element]]$class}"))
}

  • This might need an extra logical branch for rel-rel and rel-unit elements

ggplot2/R/theme.r

Lines 665 to 668 in 7e6d125

# If neither of e1 or e2 are element_* objects, return e1
if (!inherits(e1, "element") && !inherits(e2, "element")) {
return(e1)
}

  • Don't allow rel objects as 'root'-nodes in the element tree. I think the most appropriate spot to do this would be in validate_element().

validate_element <- function(el, elname, element_tree) {

Thanks for considering!

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