How to change stacking order in stacked bar chart in R?

前端 未结 1 1819
故里飘歌
故里飘歌 2020-12-07 02:51

I have a dataset like this:

> ra
   quality     GY         TH         SZ         DZ         FP
1        B 25.5932389 23.0215577 21.2171520 23.7548859 19.9         


        
相关标签:
1条回答
  • 2020-12-07 03:30

    I think quality is stacked in the original order: B, F, M and so on. I suppose it is the order of the legend what you'd like to change:

    ra.melt$quality <- factor(ra.melt$quality, levels = ra$quality)
    p <- ggplot(ra.melt, aes(x = variable, y = value))
    p + geom_bar(aes(fill = quality), stat = "identity") + 
        labs(x = "group", y = "percentage (%)")
    

    Or in reverse order:

    ra.melt$quality <- factor(ra.melt$quality, levels = rev(ra$quality))
    p <- ggplot(ra.melt, aes(x = variable, y = value))
    p + geom_bar(aes(fill = quality), stat = "identity") +  
        labs(x = "group", y = "percentage (%)")
    

    Notes

    The legend takes the levels of the factor, which are sorted alphabetically by default:

    levels(ra.melt$quality)
    # Output
     [1] "A"     "B"     "C"     "D"     "E"     "F"     "G"     
         "H"     "I"     "J"     "K"     "L"     "M"     "other"
    

    With ra.melt$quality <- factor(ra.melt$quality, levels = ra$quality) we set the order of the levels of the factor as they originally occur in the vector:

    levels(ra.melt$quality)
    #Output:
    [1] "B"     "F"     "M"     "A"     "G"     "E"     "J"   
        "D"     "C"     "I"     "K"     "L"     "H"     "other"
    
    0 讨论(0)
提交回复
热议问题