Order categorical data in a stacked bar plot with ggplot2

前端 未结 3 1652
梦毁少年i
梦毁少年i 2020-12-09 19:20

I have a matrix with the following entries:

dput(MilDis[1:200,])
structure(list(hhDomMil = c(\"HED\", \"ETB\", \"HED\", \"ETB\", \"PER\", 
\"BUM\", \"EXP\",          


        
3条回答
  •  醉梦人生
    2020-12-09 19:48

    I see that you have an order column in your data frame which I gather is your order. Hence you can simply do.

    p0 = qplot(factor(kclust), fill = reorder(hhDomMil, order), position = 'fill', 
           data = df1)
    

    Here are the elements of this code that take care of your questions

    1. How do I plot such a ordered plot? reorder
    2. How do I set up x so that each bar is "on" one number? factor(kclust)
    3. How do I seperate the bars?
    4. How do I print all kclust numbers in x? factor(kclust)

    I remember from a previous question of yours that the hhDomMil corresponded to different groups, and I suspect your ordering follows the grouping. In that case, you might want to use that information to choose a color palette that makes it simpler to follow the graph. Here is one way to do it.

    mycols = c(brewer.pal(3, 'Oranges'), brewer.pal(3, 'Greens'), 
               brewer.pal(2, 'Blues'), brewer.pal(2, 'PuRd'))
    
    p0 + scale_fill_manual(values = mycols)
    

    enter image description here

提交回复
热议问题