Подтвердить что ты не робот

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

Проблема в том, что элементы в легенде находятся не в том же порядке, что и их стеки. Цвета и цифры правильные, но порядок не соответствует. Другими словами, есть ли способ инвертировать порядок предметов в легенде? Благодаря

4b9b3361

Ответ 1

вы можете использовать новую опцию 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

Ответ 2

Добавьте + 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, но я не уверен.