2012-03-06 22 views
19

I wytwarza ułożone procent barplot z następujących danych, które znajduje się w pliku csvR: Legenda sortowania w ggplot2

,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 

zastosowaniem kodu

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

W rezultacie enter image description here

Problem polega na tym, że elementy w legendzie nie są w tej samej kolejności, co stosy, które reprezentują. Kolory i liczby są prawidłowe, ale kolejność nie jest. Innymi słowy, czy istnieje sposób odwrócenia kolejności elementów w legendzie? Dzięki

Odpowiedz

29

można użyć nowej opcji 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

Dodaj + scale_fill_hue(breaks=c("new order 1","new order 2","new order...")) jak w:

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

ja również sprawdzić http://wiki.stdout.org/rcookbook/Graphs/Legends%20(ggplot2)/ więcej.

Może się to zmieniło i stało się łatwiejsze dzięki nowemu ggplot, ale nie jestem pewien.

+1

ten robi praca z skumulowany procent barplot. –

+0

Oto zaktualizowany link do więcej informacji Legends: http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/. – nofinator

Powiązane problemy