0

I am looking for a way to create set break steps in the x-axis similar to the question posted here: Change axis breaks without defining sequence - ggplot

I noticed that the answer to that question only works because the data being plotted are named x and y in the global environment. ggplot does not appear to pass to the scales_x_continuous function the variables 'x' and 'y' defined in the aes call.

i.e. this works:

x <- 1:10
y <- 1:10

df <- data.frame(x, y)
f <- function(x) seq(min(x), max(x), by = 2)
ggplot(df, aes(x,y)) + geom_point() + scale_y_continuous(breaks = f)

But this produces the error: "...object 'x' not found"

rm(x, y) #to remove the objects x and y defined earlier
df <- data.frame("xvar" = 1:10, "yvar" = 1:10)
f <- function(x) seq(min(x), max(x), by = 2)
ggplot(df, aes(x,y)) + geom_point() + scale_y_continuous(breaks = f)

Is there a way to pass the variables defined in the aes part of the ggplot call and make the second bit of code work?

M--
  • 25,431
  • 8
  • 61
  • 93
ESELIA
  • 132
  • 1
  • 12
  • My bad. @joran is right for my reproducible example, I took a second look at my real-world problem that the example above was supposed to represent.Turns out `scale_x_continuous(breaks = f(x))` is what produces the error I mentioned above. The solution of course is `breaks = f` instead. – ESELIA Jul 08 '19 at 23:11

1 Answers1

3

You can name the variables anything, ggplot will use the values specified by which scale you are changing. See below:

library(tidyverse)

set.seed(123)

dat <- tibble(x = rdunif(10, 5, 20), 
              y = 1:10)

func <- function(bob) seq(min(bob), max(bob), 2)

dat %>% 
    ggplot(aes(x,y)) + 
    geom_point() + 
    scale_y_continuous(breaks = func) + 
    scale_x_continuous(breaks = func)

Created on 2019-07-08 by the reprex package (v0.3.0)

dylanjm
  • 2,011
  • 9
  • 21