Skip to content

setting axis aesthetics to x/y = NULL turns default axis labels into "x" / "y" instead of keeping the variable names of the next layer #6616

@sebkopf

Description

@sebkopf

I found a problem with the handling of default axis labels with layers that ignore an aesthetic by setting it to NULL. I expected the previous behavior: the default axis labels from the first layer that has those defined.

Here is a small code snippet to reproduce this bug: in all 3 cases below, the x and y axis labels should be cty and hwy but the x = NULL, y = NULL aesthetic in geom_rect turns these into x and y instead of having the labels come from top-level aes or the second0-layer geom_point() aes.

library(dplyr)
library(ggplot2)

# ggplot2 version
packageVersion("ggplot2")
#> [1] '4.0.0'

# this works to correctly set the x / y axis label defaults to hwy and cty
mpg |>
  ggplot() +
  geom_rect(
    data = function(df) {
      df |>
        filter(drv == "f") |>
        summarize(xmin = min(cty), xmax = max(cty), ymin = min(hwy), ymax = max(hwy))
    },
    map = aes(
      xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax
    )
  ) +
  geom_point(map = aes(cty, hwy))

# this does not work anymore the way it worked previously:
# define x/y aesthetics at top level and turn their use off in geom_rect with x=NULL and y=NULL
# the resulting x/y axis label defaults are now x/y instead of hwy and cty
# this happens the same way if the aesthetic is defined in geom_point and not at top-level,
# the x=NULL / y=NULL seems to cause it
mpg |>
  ggplot() +
  aes(cty, hwy) +
  geom_rect(
    data = function(df) {
      df |>
        filter(drv == "f") |>
        summarize(xmin = min(cty), xmax = max(cty), ymin = min(hwy), ymax = max(hwy))
    },
    map = aes(
      x = NULL, y = NULL,
      xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax
    )
  ) +
  geom_point()

# if it's just the geom point without the geom_rect layer, it works correctly again
mpg |>
  ggplot() +
  aes(cty, hwy) +
  geom_point()

Created on 2025-09-15 with reprex v2.1.1

Thank you for all the wonderful new features in ggplot4.0 !

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions