Skip to content

Reference lines break facet_wrap when facets are the product of a function #2963

Description

@felipegerard

I want to add some reference lines to a faceted plot. The lines should be the same in every facet. I want to use a custom value not mapped from the data. It works just fine as long as I use plain variables for faceting, but when I mix or alter them, I get an error, which depends on the operation I perform.

I think the problem lies in the fact that the plot wants to compute facets with for the non-mapped layer, but the data doesn't exist. I don't think geom_line has a problem, but rather facet_wrap.

## Example 1 ------------------------------
## Works
ggplot(mtcars, aes(mpg, cyl)) +
  geom_point() +
  geom_vline(xintercept = 20) +
  facet_wrap(vars(am))

## Doesn't work
ggplot(mtcars, aes(mpg, cyl)) +
  geom_point() +
  geom_vline(xintercept = 20) +
  facet_wrap(vars(2 * am)) # <-- there's an operation involved

## Example 2 ------------------------------
## Works
ggplot(mtcars, aes(cyl)) +
  geom_bar() +
  geom_vline(xintercept = 4.5) +
  facet_wrap(vars(am, vs))

## Doesn't work
ggplot(mtcars, aes(cyl)) +
  geom_bar() +
  geom_vline(xintercept = 4.5) +
  facet_wrap(vars(paste(am, vs))) # <-- there's an operation involved

## Easiest fix I can think of: move the operation to a mutate
mtcars %>% 
  mutate(facet = paste(am, vs)) %>% 
  ggplot(aes(cyl)) +
  geom_bar() +
  geom_vline(xintercept = 4.5) +
  facet_wrap(vars(facet))

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behaviorfacets 💎

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions