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
using the following code
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 result is
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
You can use the following syntax to change the order of the items in a ggplot2 legend: scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...) The following example shows how to use this syntax in practice.
Changing the order of legend labels can be achieved by reordering the factor levels of the Species variable mapped to the color aesthetic.
Example 1: Remove All Legends in ggplot2 We simply had to specify legend. position = “none” within the theme options to get rid of both legends.
Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.
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\nMatch") + xlab("Barcode")+ylab("Reads") + guides(fill = guide_legend(reverse = TRUE))
Add + scale_fill_hue(breaks=c("new order 1","new order 2","new order..."))
as in:
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"))
I'd also check out http://wiki.stdout.org/rcookbook/Graphs/Legends%20(ggplot2)/ for more.
This may have changed and become easier with he new ggplot but I'm not sure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With