R ggplot2重新排序特殊变量..计数

R ggplot2重新排序特殊变量..计数,r,ggplot2,R,Ggplot2,嗨,我想我这里有这个情节 Fruit <- c(rep("Apple",3),rep("Orange",25), rep("Peach",5) ) df <- data.frame(Fruit) ggplot(df, aes(Fruit, ..count..)) + geom_bar(aes(fill = Fruit), position = "dodge") 此代码将生成 然而,我真正想要的是按降序排序,这样橙色将首先跟在桃之后。我可以生成一个频率表并创建一个按级别排

嗨,我想我这里有这个情节

Fruit <- c(rep("Apple",3),rep("Orange",25), rep("Peach",5)   )


df <- data.frame(Fruit)

ggplot(df, aes(Fruit, ..count..)) + geom_bar(aes(fill = Fruit), position = "dodge")
此代码将生成

然而,我真正想要的是按降序排序,这样橙色将首先跟在桃之后。我可以生成一个频率表并创建一个按级别排序的因子,但我想知道在特殊变量本身中是否有这样做的方法

谢谢

我建议使用forcats包,首先根据频率对因子级别进行重新排序。然后你的绘图代码可以保持不变,你应该得到你想要的

library(forcats)
df$Fruit <- fct_infreq(df$Fruit)

ggplot(df, aes(Fruit, ..count..)) + 
  geom_bar(aes(fill = Fruit), position = "dodge")
试试这个ggplotdf,aesFruit,…count..+geom_baraesfill=水果,位置=道奇+比例_x_离散限制=名称可摘水果,递减=真