首页 > 解决方案 > ggplot2:组内的条形图顺序

问题描述

我有我想制作条形图的样本数据。数据将在组内组内显示。

样本数据框如下:

sample<-data.frame("Flag"=c(TRUE,TRUE,TRUE,TRUE,TRUE,FALSE),
        "type"=c("Best","Normal","Dormant","Lost","Cheap","Normal"), 
        "n" =c(9859,5008,3807,1747,1085,992))

我想在列的Flagorder by内制作条形图。Ntype

这是制作情节:

make_plot <-ggplot2::ggplot( sample, aes(fill=reorder(type,n), x=Flag, y=n)) +  
    geom_bar(position="dodge", stat="identity") 

make_plot

我不明白如何使用带因子的重新排序。或重新排序的因素

sample$type <-factor(sample$type, 
   levels=c("Best","Normal","Dormant","Lost","Cheap","Normal"))

它会给出错误,因为级别中有重复项。

我该如何解决这个问题?

标签: rggplot2

解决方案


fct_inorderfrom forcatspackage 是你需要的:

library(ggplot2)
library(forcats)
ggplot(sample, aes(fill = fct_inorder(type), x=Flag, y=n)) +  
        geom_bar(position="dodge", stat="identity") 

在此处输入图像描述


推荐阅读