Skip to content

Linewidth not considered in legend key sizing #5160

@teunbrand

Description

@teunbrand

This is just to report a small regression since ggplot2 3.4.0.
Previously, having thick lines would resize the legend key to fit the size of the line.

# devtools::install_version("ggplot2", "3.3.0")
library(ggplot2)

df <- data.frame(
  x = c(0, 1, 0, 1),
  y = c(0, 0, 1, 1),
  grp = c("A", "A", "B", "B")
)

ggplot(df, aes(x, y, size = grp, colour = grp)) +
  geom_line() +
  scale_size_manual(values = c(10, 20))

Created on 2023-01-25 with reprex v2.0.2

Currently, the legend keys only take size into account, but not linewidth. In some cases, this can cause legends to become misleading. In the example below, the salmon coloured line is much thicker than visually displayed in the legend, because it underlaps the turquoise line.

library(ggplot2)

df <- data.frame(
  x = c(0, 1, 0, 1),
  y = c(0, 0, 1, 1),
  grp = c("A", "A", "B", "B")
)

ggplot(df, aes(x, y, linewidth = grp, colour = grp)) +
  geom_line() +
  scale_discrete_manual("linewidth", values = c(10, 20))

Created on 2023-01-25 with reprex v2.0.2

I think the relevant line in the legend drawing code lives here (it extracts the size in mm and converts it to cm):

key_size <- lapply(guide$geoms, function(g) g$data$size / 10)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorguides 📏

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions