在水平堆叠条形图(R)中重新排序堆栈

时间:2016-04-05 23:32:50

标签: r ggplot2

我正在尝试使用ggplot制作水平堆叠条形图。以下是我的数据框中300个站点中的3个站点的实际值。这是我到目前为止所处的位置,使用从这些previous questions中提取的信息,我承认我可能还没有完全理解。

"location.coordinates"

生成此图。

initial ggplot result

  1. 我想要做的是重新排序这些条形图,使它们按农业类别的值按降序排列 - 在这个例子中,AR002将位于顶部,然后是AR003,然后是AR001。我尝试将aes的内容更改为df <- data.frame(id=c("AR001","AR001","AR001","AR001","AR002","AR002","AR002","AR003","AR003","AR003","AR003","AR003"), landuse=c("agriculture","developed","forest","water","agriculture","developed","forest","agriculture","developed","forest","water","wetlands"), percent=c(38.77,1.76,59.43,0.03,69.95,0.42,29.63,65.4,3.73,15.92,1.35,13.61)) df id landuse percent 1 AR001 agriculture 38.77 2 AR001 developed 1.76 3 AR001 forest 59.43 4 AR001 water 0.03 5 AR002 agriculture 69.95 6 AR002 developed 0.42 7 AR002 forest 29.63 8 AR003 agriculture 65.40 9 AR003 developed 3.73 10 AR003 forest 15.92 11 AR003 water 1.35 12 AR003 wetlands 13.61 str(df) 'data.frame': 12 obs. of 3 variables: $ id : Factor w/ 3 levels "AR001","AR002",..: 1 1 1 1 2 2 2 3 3 3 ... $ landuse: Factor w/ 5 levels "agriculture",..: 1 2 3 4 1 2 3 1 2 3 ... $ percent: num 38.77 1.76 59.43 0.03 69.95 ... df <- transform(df, landuse.ord = factor( landuse, levels=c("agriculture","forest","wetlands","water","developed"), ordered =TRUE)) cols <- c(agriculture="maroon",forest="forestgreen", wetlands="gold", water="dodgerblue", developed="darkorchid") ggplot(df,aes(x = id, y = percent, fill = landuse.ord, order=landuse.ord)) + geom_bar(position = "stack",stat = "identity", width=1) + coord_flip() + scale_fill_manual(values = cols) ,但这消除了堆叠,似乎可以将每个土地利用类别的百分比加总:
  2. second ggplot result

    1. 我想按顺序排列堆栈,从左到右:农业,森林,湿地,水,发达。我尝试使用代码的aes(x = reorder(landuse.ord, percent)部分,在图例中将其按正确的顺序排列,但不在绘图本身中?
    2. 提前感谢...我根据其他人的问题答案取得了很多进展,但现在似乎已经停滞不前了!

      更新:这是所有326个网站的完成图表! finished graph

1 个答案:

答案 0 :(得分:2)

根据您的意见,我相信这是您的解决方案。将这些行放在cols&lt; -...:

之后
  #create df to sort by argiculture's percentage
ag<-filter(df, landuse=="agriculture")
  #use the df to sort and order df$id's levels
df$id<-factor(df$id, levels=ag$id[order(ag$percent)], ordered = TRUE)
  #sort df, based on ordered ids and ordered landuse
df<-df[order(df$id, df$landuse.ord),]

ggplot(df,aes(x = id, y = percent, fill = landuse.ord, order=landuse.ord)) + 
    geom_bar(position = "stack",stat = "identity", width=1) + 
    coord_flip() +
    scale_fill_manual(values = cols) 

评论应阐明每一行的目的。这将重新排序原始数据框,如果这是一个问题,我会创建一个副本,然后对新副本进行操作。