13

我注意到在使用 plot 创建的直方图中填充条形的默认设置是反向字母顺序,而图例则按字母顺序排列。我有什么办法让两者都按字母顺序排列?问题在下面的示例图中很明显。额外的问题:我如何将从左到右的条形顺序从字母顺序更改为递减计数?谢谢

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")

在此处输入图像描述

我试图从高到低排序计数和填充颜色,以便它们与图例的字母顺序相匹配。我一直在尝试使用最初帖子中的提示调整它几个小时,但没有成功。对此的任何帮助将不胜感激!!!

4

1 回答 1

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))

在此处输入图像描述

要恢复字母顺序,请在上述代码之前对 Group 因子进行重新排序:

# 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))

在此处输入图像描述

对于奖金(通过减少总计数来排序条形图),重新排序 Site 变量的因子顺序:

# 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))

在此处输入图像描述

于 2012-07-23T16:17:06.840 回答