I have data in a csv file in the following format
,BC1,BC10,BC11
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
I acquire the data in the following way
data <- read.csv(file="file.csv",sep=",",header=TRUE)
data <- data[,2:ncol(dat)]
Then transform it
datam <- melt(cbind(data,ind=rownames(data)),is.var = c('bind'))
Then I create a stacked percent plot
ggplot(datam,aes(x = variable, y = value,fill = ind)) +
geom_bar(position = "fill") +
scale_y_continuous(labels = percent_format())
To which I get:

I am trying to order the values in the legend that should go (1…16) instead of 1,10,…,16,2…,9. The color order is correct in the legend though. Thanks
It’s because
ind(your fill variable) is being sorted as a string factor.You can convert
indto numeric and then use it as the fill argument:However this does give
factor(ind)as the title for the legend. You could do:Or, you could just use
scale_fill_discrete('My Legend Name')and avoid having to convertdatam, e.g.:Edit
The ordering of the legend labels is determined by
levels(datam$ind):That’s why you originally got the string-wise order.
By doing
factor(as.numeric(ind)),levels(datam$ind)got re-sorted in numeric order.So to specify them going from 16 to 1, say, you can do:
Hmm, that did change the colours/stacking order though. I’m unsure how to have the labels go one way but the stacking go the other — ggplot always has them in sync (ie if labels are 1:16, then so is the stacking order). Re switching the colours around, I’m sure there’s some ggplot way to reverse the colour scale, probably via
scale_colour_manual(as that’s just a cosmetic change) – I don’t know how to do that myself though.