title: r-legend in stacked bar plot
body: <p>I'm relatively new to R and struggling to get my legend in the correct place. I've had a good look online and just can't seem to figure it out.</p>
  
  <pre><code>#  rating no  yes
  #    1   140  38
  #    2   72   46
  #    3   46   62
  #    4   42   140
  #    5   16   32
  </code></pre>
  
  <p>I created a table (tab10) as above and then created a stacked proportional barplot using the following code:</p>
  
  <pre><code>prop = prop.table(tab10,margin=2)
  barplot(tab10, names.arg=c("Non-CBFM", "CBFM"), 
  ylab="count", legend=c("much worse", "worse", "no change", "better", "much better"))
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/0xK3b.jpg" alt="Shows graphic with legend overlap"> </p>
  
  <p>Clearly the legend placement is a problem.</p>
  
  <p>Per the suggestion of another post, I created a new csv file listing my categorical columns as names (as opposed to converting to factors).</p>
  
  <p>This one, however, orders the Rating column alphabetically as oppossed to the original scale (1-5). </p>
  
  <p><img src="https://i.stack.imgur.com/vt36d.jpg" alt="Shows graphic with good legend placement but incorrect order of Rating column"></p>
  
  <pre><code>d3 &lt;- read.csv("Water.csv")
  attach(d3)
  levels(CBFM)
  #[1] "CBFM"     "Non-CBFM"
  levels(Rating)
  #[1] "better"      "much better" "much worse"  "no change"       "worse"      
  data=Count
  data=matrix(data,ncol=2,byrow=TRUE)
  colnames(data)=levels(CBFM)
  rownames(data)=levels(Rating)
  
  #create table based on proportions of columns
  prop = prop.table(data,margin=2)
  barplot(prop, col=heat.colors(length(rownames(prop))), width=2)
  legend("topright", inset=c(-0.25,0),             
  fill=heat.colors(length(rownames(prop))),
  legend=rownames(data))
  </code></pre>
  
  <p>Is someone able to assist?</p>
  
  <p>Many thanks!</p>