title: Create a different color scale for each bar in a ggplot2 stacked bar graph
body: <p>I have a stacked bar chart that looks like this: </p>
  
  <p><a href="https://i.stack.imgur.com/3Lncc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Lncc.png" alt="Number of patients on each drug by drug class"></a></p>
  
  <p>While the colors look nice, it is confusing to have so many similar colors representing different drugs. I would like to have a separate color palette for each bar in the graph, for example, class1 could be use the palette "Blues" while class2 could use the palette "BuGn" (color palette names found <a href="http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/#a-colorblind-friendly-palette" rel="nofollow noreferrer">here</a>)</p>
  
  <p>I have found some instances in which people manually coded colors for each bar (such as <a href="https://stackoverflow.com/questions/22781685/different-colors-for-each-bar-in-stacked-bar-graph-base-graphics">here</a>), but I'm not sure if what I'm asking is possible - these bars would need to be based on palettes, since there are so many drugs in each drug class.</p>
  
  <p><strong>Code to create the above graph:</strong></p>
  
  <pre><code>library(ggplot2)
  library(plyr)
  library(RColorBrewer)
  
  drug_name &lt;- c("a", "a", "b", "b", "b", "c", "d", "e", "e", "e", "e", "e", "e",
             "f", "f", "g", "g", "g", "g", "h", "i", "j", "j", "j", "k", "k",
             "k", "k", "k", "k", "l", "l", "m", "m", "m", "n", "o")
  df &lt;- data.frame(drug_name)
  
  #get the frequency of each drug name
  df_count &lt;- count(df, 'drug_name')
  
  #add a column that specifies the drug class
  df_count$drug_class &lt;- vector(mode='character', length=nrow(df_count))
  
  df_count$drug_class[df_count$drug_name %in% c("a", "c", "e", "f")] &lt;- 'class1'
  
  df_count$drug_class[df_count$drug_name %in% c("b", "o")] &lt;- 'class2'
  
  df_count$drug_class[df_count$drug_name %in% c("d", "h", "i")] &lt;- 'class3'
  
  df_count$drug_class[df_count$drug_name %in% c("g", "j", "k", "l", "m", "n")] &lt;- 'class4'
  
  #expand color palette (from http://novyden.blogspot.com/2013/09/how-to-expand-color-palette-with-ggplot.html)
  
  colorCount = length(unique(df_count$drug_name))
  getPalette = colorRampPalette(brewer.pal(9, "Set1"))
  
  test_plot &lt;- ggplot(data = df_count, aes(x=drug_class, y=freq, fill=drug_name) ) + geom_bar(stat="identity") + scale_fill_manual(values=getPalette(colorCount))
  
  test_plot
  </code></pre>