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

查看:85
本文介绍了在 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
Match")  +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:

you can use a new option 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
Match") + xlab("Barcode")+ylab("Reads") +
  guides(fill = guide_legend(reverse = TRUE))

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

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