简体   繁体   中英

Strange behavior of reorder function in R

This simple example demonstrates how well the reorder command works:

library(ggplot2)    
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
ggplot(df, aes(reorder(Category, -Count), Count)) + geom_bar(stat = "identity")

If I apply the same syntax to different data the reordering does not work. See this example:

ggplot(mpg, aes(reorder(manufacturer, -hwy), hwy)) + geom_bar(stat = "identity")

The order seems quite random on the second example, and the first example is clearly descending. What's the difference? And how is the second example ordering things? I can't figure it out.

Your first dataframe df is already aggregated, while mpg is not. So you should first aggregate your dataframe before you reorder the factor levels, try:

library(dplyr)
mpg <- mpg %>% group_by(manufacturer) %>% summarize(hwy=sum(hwy))
ggplot(mpg, aes(reorder(manufacturer, -hwy), hwy)) + geom_bar(stat = "identity")

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM