首页 > 解决方案 > 使用 as.factor 时在 ggplot2 中重新排序条形图输出

问题描述

我希望有人能帮忙。

我有一个DF如下:

Year   Winner
1930  Uruguay    
1934  Italy    
1938  Italy    
1950  Uruguay    
1954  Germany FR    
1958  Brazil    
1962  Brazil    
1966 England    
1970  Brazil    
....

等等

我想要做的是用 ggplot2 创建一个条形图,但重新排序它,以便获胜者数量最多的国家排在第一位。

我用来生成当前图表的代码是:

ggplot(data, aes(x=as.factor(Winner), fill=as.factor(Winner) )) + 
geom_bar() + 
theme(legend.position = "none")

我知道有一些关于重新排序的事情,但我无法让它与 as.factor 参数一起工作。

谢谢

标签: rggplot2

解决方案


我使用 forcats 解决了这个问题

    require(forcats)
    ggplot(data, aes(fct_infreq(Winner),  fill=as.factor(Winner))) +
    geom_bar()+
    theme(legend.position = "none")

推荐阅读