[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
Fri Dec 31 01:11:56 CET 2021


 Thank you all of your help. I'm new in R. I'll follow Bert's and your suggestions to post the question in another area in future. 
Happy New Year
Kai
    On Thursday, December 30, 2021, 02:05:12 PM PST, CALUM POLWART <cpolwart using chemo.org.uk> wrote:  
 
 You will get shot down in flames for posting this here. This list is for base-R and your query is tidyverse related so belongs on somewhere tidy specific...
But...
mpg[[y]]
Is returning the column mpg[[y]] unfiltered but displ is filtered.
It would be possible to use mpg[[y]][ mpg$hwy<35]
But I suspect there is a better solution involving . As a data source or perhaps select to pick only the data you want...

On 30 Dec 2021 18:42, Kai Yang via R-help <r-help using r-project.org> wrote:


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]]

______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



  
	[[alternative HTML version deleted]]



More information about the R-help mailing list