[R] question about error message: "Aesthetics must be either length 1 or the same as the data (226): y and colour"

Kai Yang y@ngk@|9999 @end|ng |rom y@hoo@com
Thu Dec 30 19:42:43 CET 2021


Hi R team,
I can create a plot using the code below:
library(ggplot2)
library(dplyr)
mpg %>%
  filter(hwy <35) %>% 
  ggplot(aes(x = displ, y = hwy, color = cyl)) + 
  geom_point()
ggsave("c:/temp/hwy_cyl.jpg",width = 9, height = 6, dpi = 1200, units = "in")


I want to do the exactly same work using function. Below is the function I created:
plot1 <- function(y, c, f){
          mpg %>%
            filter(hwy <35) %>% 
            ggplot(aes(x = displ, y = mpg[[y]], color = mpg[[c]] )) + 
            geom_point()  
          ggsave(paste0("c:/temp/", f ,".jpg"), width = 9, height = 6, dpi = 1200, units = "in")  
} 
plot1("hwy","cyl","hwy_cyl_f")

But I got error message when I run the code: "Aesthetics must be either length 1 or the same as the data (226): y and colour" . I checked online about the message. My understanding is: I need to add "fill" in geom_point() statement. My questions are:
1. is it possible to make the code work without add 'fill' in geom_point() statement, but keep the color as same as the first code? 
2. if I must add 'fill' option in geom_point() statement, how to add them in? Should I add 266 colors name after 'fill'?
3. this is my first function in R, I'm sure there are many problems in the code. please point out my error in the code.


Thank you,
Kai

	[[alternative HTML version deleted]]



More information about the R-help mailing list