Search code examples
rggplot2geom-bar

Reordering columns in ggplot2, Error: Mapping should be created with `aes() or `aes_()`


I'm trying to reorder my columns in ggplot, to go from min to max, but keep getting this error message

countries<-c("Australia", "Austria", "Belgium", "Canada", "Denmark", "France" ,"Germany", "Italy","Luxembourg" ,"Netherlands","Norway", "New Zealand","Spain","Sweden","United Kingdom","USA")
cost<-c(1221,711,184,250,6658,51,1118,880,919,2500,1558,2452,103,920,1460,401)
citcost<-data.frame(countries, cost)

citcost %>% ggplot(citcost, aes(x=reorder(countries, cost), y=cost, fill=countries)) + geom_bar(stat="identity") + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + scale_colour_brewer()

Error: Mapping should be created with aes() or aes_()`.


Solution

  • The issue is with the arguments of ggplot. Here, the second argument is mapping and it expects aes, instead we are providing the data object with ggplot(citcost) while the data is already passed in via cicost %>% ggplot. Thus, the ggplot, call in the OP's code is

    ggplot(data = citcost, mapping = citcost, ...)
    

    Instead it would be

    citcost %>%
        ggplot(aes(x=reorder(countries, cost), y=cost, fill=countries)) + 
           geom_bar(stat="identity") + 
           theme(axis.text.x = element_text(angle = 45, hjust = 1)) + 
           scale_colour_brewer()
    

    -output

    enter image description here