在ggplot2中对图例进行排序 [英] Sort legend in ggplot2

查看:678
本文介绍了在ggplot2中对图例进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从csv文件中的以下数据中生成了堆积百分比条形图,

I have produced a stacked percent barplot from the following data, which is in a csv file,

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

结果是

问题在于,图例中的项目与它们表示的堆栈的顺序不同.颜色和数字正确,但顺序不正确.换句话说,是否有一种方法可以反转图例中项目的顺序?谢谢

The problem is that the items in the legend are not in the same order as the stacks they represent. The colours and the numbers are right but the order is not. In other words, is there a way to invert the order of the items in the legend? Thanks

推荐答案

您可以使用新选项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))

这篇关于在ggplot2中对图例进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆