sstww
sstww

Reputation: 699

simple custom plotting function using ggplot2: Error: Aesthetics must be either length 1 or the same as the data

The following works, it plots one column data based on the order of the data:

s<-data.frame(t=c(3, 50, 20, 100, 7, 80))
ggplot(s, aes(y=s$t, x=seq(1, length(s$t)))) + 
  geom_point()+
  geom_hline(yintercept =10)

since I have many such data, I would like to put it in a function so that I can reuse it, as such:

plot1<-function(a, b, c){
  ggplot(a, aes(y=a$b, x=seq(1, length(a$b)))) + 
  geom_point()+
  geom_hline(yintercept =c) 
  }

However, the following does not work:

s<-data.frame(t=c(3, 50, 20, 100, 7, 80))
plot1(s, t, 10)

Instead, it produced this error message: Error: Aesthetics must be either length 1 or the same as the data (6): x, y

What went wrong?

Upvotes: 0

Views: 890

Answers (1)

Roland
Roland

Reputation: 132706

Do not use $ within aes. It looks within the data.frame specified as data for the variables using non-standard evaluation. If you use $ you can get unexpected results.

I don't know any ggplot2 examples that use $ within aes.

Here you can use aes_q:

plot1<-function(a, b, c){
  a$x <- seq_len(nrow(a))
  ggplot(a, aes_q(y=substitute(b), x=quote(x))) + 
    geom_point()+
    geom_hline(yintercept = c) 
}

plot1(s, t, 10)

resulting plot

Upvotes: 5

Related Questions