Error: Aesthetics must be either length 1 or the same as the data (5): y

Viewed 68

I'm trying to run this code but it keeps saying

Error: Aesthetics must be either length 1 or the same as the data (5): y

and I have no idea why. I have looked at other questions with similar errors but I still don't get it:

flights = read.csv("http://www.maths.usyd.edu.au/u/UG/JM/DATA1001/r/current/projects/2020data/flights.csv")

library(ggplot2)
library(dplyr)
library(plotly)

newdata = subset(flights, Year >= 2010)
average_flights = newdata %>%
  filter(Year >= "2010" & Year <= "2021")%>%
  filter(Month_num >= 1 &Month_num !=12) %>%
  group_by(Month_num)%>%
  summarise(sum_flights = sum(All_Flights))

myflights2 = flights %>% 
  filter(Year >= "2010" & Year <= "2021") %>%
  group_by(Airline) %>%
  count() %>%
  arrange(desc(n)) %>%
  head(5) %>%
  ggplot(myflights2, mapping = aes(x = Airline, y = average_flights, fill(In_Out))) + 
         geom_bar() +
         ggtitle("Average Number of Flights Each Month Per Airline")
ggplotly(myflights2)
1 Answers

Ok after our discussion here is what you need to do :

flights2= flights %>% filter(Year>=2010)
flights2$new= paste(flights2$Year, flights2$Month_num)
e = function(i){
  a = flights2[flights2$In_Out==i,]
  b = lapply(unique(a$Airline), function(j){
    return(c(i,j,mean(table(a[a$Airline==j,new]))))
  })
  return(t(as.data.frame(b)))
}
b = lapply(unique(flights2$In_Out), e)
b = rbind(b[[1]],b[[2]])
b = as.data.frame(b)
d = c()
for(i in unique(b$V2)){
  d = c(d, setNames(sum(as.numeric(b[b$V2==i,"V3"])),i))
}
c= b[b$V2%in% names(sort(d,decreasing = T)[1:5]),]
c$V3=as.numeric(c$V3)
ggplot(c,aes(x=V2,y=V3, fill=V1))+
  geom_bar(stat = 'identity', position = 'dodge')

the output is

enter image description here

Related