简体   繁体   中英

GGplot scale_fill_manual() unexpected behaviour

Edit* Assume I've been down-voted due to not being replicable, fair enough though these are often complex/sensitive data sets and I wanted to be cautious.

That being said I solved this by setting the factor levels of the fill= call in GGplot. Still not 100% sure why this works (ie how this affected colour order), will do some research and find out.

Having an issue with manually setting colour in a bar plot using scale_fill_manual

So I feed a list of colours into a bar plotting routine, which pulls data from a code frame (ie scores for a list of names), appends a score at the top and bottom of that list (ie an average and a benchmark), then sets colours to be a rainbow spectrum (depending on number of names) with set colours for the top and bottom bars average and benchmark (blue and gold)

My issue is that the colours are out of order somehow...

plotdata <- subset(groupdata,scale.code==(k)&year!=prior.year) #select data for the given scale
#create the plot for the scale
curr.plot <- ggplot(plotdata, aes(x = FBMA_ID, y = Plot.score, fill=FBMA_ID))+ 
  geom_bar(width=0.7, stat="identity") +  
  theme(legend.position="none") +
  coord_flip() +
  scale_x_discrete(limits = rev(unique(plotdata$FBMA_ID)))+
  scale_y_continuous(limit = MMlimits, oob=squish, minor_breaks = value.breaks.minor, 
                     breaks = value.breaks.major, labels = value.labels, expand = c(0,0)) +
  scale_fill_manual(values=rev(temp.col))+

note that the colours used (ie temp.col ) output like this, in the correct order

 [1] "gold"        "#BFFF80"    
 [3] "#9FFF80"     "#80FF80"    
 [5] "#80FF9F"     "#80FFBF"    
 [7] "#80FFDF"     "#80FFFF"    
 [9] "#80DFFF"     "#80BFFF"    
[11] "#809FFF"     "#8080FF"    
[13] "#9F80FF"     "#BF80FF"    
[15] "#DF80FF"     "#FF80FF"    
[17] "#FF80DF"     "#FF80BF"    
[19] "#FF809F"     "#FF8080"    
[21] "#FF9F80"     "#FFBF80"    
[23] "dodgerblue4"

though the plot outputs as this

在此处输入图片说明

with the first and last colours now second and second last.

I've probably missed something glaring, long day!

I can do a dput if required.

Cheers, Alex

Setting the factor levels in the plotdata frame as per below solved this. Thanks to Roman Luštrik for the guidance ad contribution.

ggplot(plotdata, aes(x = FBMA_ID, y = Plot.score, fill=factor(plotdata$FBMA_ID, levels = names))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM