1

Hoping to set two different color schemes for my ggplot based on a value in a certain column.

This is my data:

itemName = c("item1", "item2", "item3", "item4","item5", "item1", "item2", "item3", "item4", "item5") 
MPindex = c(124, 118, 101, 112, 126, 124, 118, 101, 112, 126)
code = c("A", "A", "A", "A", "B", "A", "A", "A", "A", "B")
topTwo = c(55.6, 53,45.2, 50.2, 56.2, 55.6, 53, 45.2, 50.2, 56.2)
variable = c(4, 4, 4, 4, 4, 5, 5, 5, 5, 5) 
value = c(37.2, 36.2, 31.4, 31.2, 34.2, 18.4, 16.8, 13.8, 19, 22)

testNew<-data.frame(itemName,MPindex,code,topTwo,variable,value)

And this is as close as I've gotten with the graph I want:

enter image description here

What I want though, is for the item with code=="B" to have different scale_fill_manual values. Note the order of the bars might change and the itemNames might change since this is reactive within a shiny app, so rather than manually setting item5 bar to be different, I really need it to go off of the "code" column.

Current graph code:

  p14 = ggplot(data = testNew, aes(x=reorder(itemName,-MPindex),y=value,fill=variable))+blank_theme+
geom_bar(stat="identity")+geom_text(aes(label=paste(value,"%")),vjust=1.2,colour='white')+theme(axis.text.x = element_text(angle = 45,hjust=1.00,vjust = 1.15))+
xlab("")+scale_fill_manual(values = c("#33CCCC","#00A499"))

blank_theme <- theme_minimal()+
  theme(
    axis.text.y = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
   plot.title=element_text(size=14, face="bold")
  )

p14

And I want the code=="B" item to always have scale_fill_manual(values=c("lightgrey","grey").

Thanks in advance! :)

SarahGC
  • 487
  • 1
  • 8
  • 19
  • 2
    It sounds like `fill` should be based on the combination of `code` and `variable`. Then you could give a named vector of colors to `scale_fill_manual`. It could look something like `values = c("A.4" = "#33CCCC", "A.5" = "#00A499", "B.4" = "lightgrey", "B.5" = "grey") `. If you want a more concrete example, please paste your dataset into your question instead of putting a picture of the dataset. – aosmith Jul 31 '17 at 16:32
  • Thanks! I added testNew$color<-paste0(testNew$code,".",testNew$variable) and then was able to use fill= color and your suggestion. And, do you know of a quick way to give code to generate my data set? Rather than typing out vectors with all of the values in the data frame? – SarahGC Jul 31 '17 at 16:39
  • You can use `dput()` https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – S Rivero Jul 31 '17 at 16:44
  • thanks. never new about dput. – SarahGC Jul 31 '17 at 16:55

0 Answers0