在ggplot2中对图例进行排序

时间:2012-03-06 03:55:33

标签: r ggplot2

我从以下数据中生成了堆积百分比条形图,该数据位于csv文件中,

,ONE,TWO,THREE
1,2432,420,18
2,276,405,56
3,119,189,110
4,90,163,140
5,206,280,200
6,1389,1080,1075
7,3983,3258,4878
8,7123,15828,28111
9,8608,48721,52576
10,9639,44725,55951
11,8323,45695,32166
12,2496,18254,26600
13,1524,8591,18583
14,7861,1857,1680
15,10269,5165,4618
16,13560,64636,63262

使用以下代码

library(ggplot2)
library(reshape2)
library(scales)

data <- read.csv(file="file.csv",sep=",",header=TRUE)
data <- data[,2:ncol(data)]
datam <- melt(cbind(data,ind = sort(rownames(data))),is.var = c('ind'))
datam$ind <- as.numeric(datam$ind)
ggplot(datam,aes(x = variable, y = value,fill = factor(as.numeric(ind)))) +
geom_bar(position = "fill") + scale_y_continuous(labels =percent_format()) +
scale_fill_discrete("Barcode\nMatch")  +xlab("Barcode")+ylab("Reads")

结果是 enter image description here

问题是图例中的项目与它们所代表的堆栈的顺序不同。颜色和数字是正确的,但顺序不是。换句话说,有没有办法颠倒图例中项目的顺序?感谢

2 个答案:

答案 0 :(得分:30)

您可以使用新选项reverse = TRUE

ggplot(datam,aes(x = variable, y = value,fill = factor(as.numeric(ind)))) +
  geom_bar(position = "fill") + scale_y_continuous(labels =percent_format()) +
  scale_fill_discrete("Barcode\nMatch") + xlab("Barcode")+ylab("Reads") +
  guides(fill = guide_legend(reverse = TRUE))

enter image description here

答案 1 :(得分:3)

添加+ scale_fill_hue(breaks=c("new order 1","new order 2","new order...")),如下所示:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, fill=group)) + geom_bar() + 
    geom_bar(colour="black", legend=FALSE) + 
    scale_fill_hue(breaks=c("trt1","ctrl","trt2"))

我还要查看http://wiki.stdout.org/rcookbook/Graphs/Legends%20(ggplot2)/了解更多信息。

对于新的ggplot,这可能已经改变并变得更容易,但我不确定。