Search code examples
rggplot2axes

R-style axes with ggplot - again


I have the same question that was posted here earlier: R-style axes with ggplot I have tried the solution which was suggested by baptiste:

library(ggplot2)

d <- data.frame(x=1:10, y=rnorm(10))

base_breaks_x <- function(x){
  b <- pretty(x)
  d <- data.frame(y=-Inf, yend=-Inf, x=min(b), xend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend)),
       scale_x_continuous(breaks=b))
}
base_breaks_y <- function(x){
  b <- pretty(x)
  d <- data.frame(x=-Inf, xend=-Inf, y=min(b), yend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend)),
       scale_y_continuous(breaks=b))
}

ggplot(d, aes(x,y)) +
  geom_point() +
  theme_bw() +
  opts(panel.border = theme_blank(),
       panel.grid.major = theme_blank(),
       panel.grid.minor = theme_blank()) +
  base_breaks_x(d$x) +
  base_breaks_y(d$y)

and found that this is only working when the plot aesthetics just consists of aes(x,y). Drawing data from a frame where one column contains a factor by which the colour is changed, e.g.

d <- data.frame(x=1:10, y=rnorm(10),name=rep(c("blue","red"),5))
ggplot(d, aes(x,y,colour=name))+ ...

gives the error message

"Error in eval(expr, envir, enclos) : object 'name' not found"

How can this problem be solved?

Thank you very much for your help!


Solution

  • You got this error because you set colour=name inside the ggplot() call and base_breaks_x() and base_breaks_y() contains geom_segment() calls that also tries to find variable name inside the dataframes of those functions. There are two ways to solve the problem.

    First, move colour=name from ggplot() to aes() of geom_point().

    ggplot(d, aes(x,y)) +
      geom_point(aes(colour=name))
    

    Second, modify functions base_breaks_x() and base_breaks_y() by adding inherit.aes=FALSE inside the geom_segment() calls.

    geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend),inherit.aes=FALSE)