ggplot2中直方图条的反向填充顺序

时间:2012-07-23 13:54:45

标签: r ggplot2

我注意到,使用绘图创建的直方图中填充条形的默认值是反向字母顺序,而图例按字母顺序排序。我有什么方法可以按字母顺序排序吗?问题在下面的示例图中很明显。奖金问题:我如何将从左到右的条形顺序从字母顺序更改为递减计数总数?感谢

df <- data.frame(
  Site=c("A05","R17","R01","A05","R17","R01"),
  Group=c("Fungia","Fungia","Acro","Acro","Porites","Porites"),
  Count=c(6,8,6,7,2,9),
  Total=c(13,10,15,13,10,15)
)

  Site   Group Count Total
1  A05  Fungia     6    13
2  R17  Fungia     8    10
3  R01    Acro     6    15
4  A05    Acro     7    13
5  R17 Porites     2    10
6  R01 Porites     9    15

qplot(df$Site,data=df,weight=df$Count,geom="histogram", fill=df$Group, ylim = c(0,16)) + 
  xlab("Sites") + 
  ylab("Counts") + 
  scale_fill_hue(h=c(0,360), l=70, c=70,name = "Emergent Groups")

enter image description here

我正在尝试将计数从高到低和填充颜色排序,以便它们匹配图例的字母顺序。我一直试图用初始帖子的提示调整它几个小时但没有成功。任何有关这方面的帮助将非常感谢!!!

1 个答案:

答案 0 :(得分:18)

如果您只想要颜色顺序匹配,则可以反转图例:颜色顺序将匹配,但图例将按反向字母顺序排列:

qplot(df$Site,data=df,weight=df$Count,geom="histogram", fill=df$Group, ylim = c(0,16)) + 
  xlab("Sites") + 
  ylab("Counts") + 
  scale_fill_hue(h=c(0,360), l=70, c=70,name = "Emergent Groups") +
  guides(fill = guide_legend(reverse = TRUE))

enter image description here

要获得字母顺序,请在上面的代码之前重新排序组因子:

# reorder the groups
df$Group <- factor(df$Group , 
                   levels=levels(df$Group)[order(levels(df$Group), decreasing = TRUE)])

qplot(df$Site,data=df,weight=df$Count,geom="histogram", fill=df$Group, ylim = c(0,16)) + 
  xlab("Sites") + 
  ylab("Counts") + 
  scale_fill_hue(h=c(0,360), l=70, c=70,name = "Emergent Groups") +
  guides(fill = guide_legend(reverse = TRUE))

enter image description here

对于奖金(通过减少总计数来排序金条),重新排序网站变量的系数顺序:

# reorder the sites
df$Site <- factor(df$Site, 
                  levels = levels(df$Site)[order(aggregate(Count ~ Site, data = df, sum)$Count, 
                                                 decreasing = TRUE)])
# reorder the groups
df$Group <- factor(df$Group , 
                   levels=levels(df$Group)[order(levels(df$Group), decreasing = TRUE)])

qplot(df$Site,data=df,weight=df$Count,geom="histogram", fill=df$Group, ylim = c(0,16)) + 
  xlab("Sites") + 
  ylab("Counts") + 
  scale_fill_hue(h=c(0,360), l=70, c=70,name = "Emergent Groups") +
  guides(fill = guide_legend(reverse = TRUE))

enter image description here