【问题标题】:Reorder Columns/Legend [duplicate]重新排序列/图例 [重复]
【发布时间】:2021-10-09 08:36:36
【问题描述】:
Country_Of_Data Year  Appr_Country Apprehension
##    <chr>           <chr> <chr>       <dbl>
##  1 Afghanistan     2010  PAN          17
##  2 Afghanistan     2011  PAN           0
##  3 Afghanistan     2010  MEX           3
##  4 Afghanistan     2011  MEX           4
##  5 Afghanistan     2010  US            0
##  6 Afghanistan     2011  US            19
ggplot(Afghan_Appr, aes(Year, Apprehension, fill = Appr_Country)) + geom_bar(stat = "identity", position = 'dodge')

我的输出图基本上每年绘制三个条形图,但是当我希望它是 PAN、MEX、US 时,它按 MEX、PAN、US 的顺序进行。有没有办法切换顺序?我尝试使用 Afghan$Appr_Country 切换顺序,但由于数据结构的原因,它不起作用。

【问题讨论】:

    标签: r ggplot2 legend geom-bar


    【解决方案1】:

    这行得通吗?

    Afghan_Appr[,3] = factor(Afghan_Appr[,3], level= c('PAN','MEX','US'))
    ggplot(Afghan_Appr, aes(Year, Apprehension, fill = Appr_Country)) + geom_bar(stat = "identity", position = 'dodge')
    

    【讨论】:

      【解决方案2】:

      使用forcats包中的fct_relevel切换df的顺序

      library(ggplot2)
      library(forcats)
      
      ggplot(Afghan_Appr, aes(x = Year, y = Apprehension, fill = fct_relevel(Appr_Country, c("PAN", "MEX", "US")))) +
        geom_bar(stat = "identity", position = "dodge")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-18
        • 1970-01-01
        • 1970-01-01
        • 2018-11-27
        • 2017-04-28
        • 1970-01-01
        • 2011-10-31
        • 1970-01-01
        相关资源
        最近更新 更多