4

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.

#  rating no  yes
#    1   140  38
#    2   72   46
#    3   46   62
#    4   42   140
#    5   16   32

I created a table (tab10) as above and then created a stacked proportional barplot using the following 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"))

Shows graphic with legend overlap

Clearly the legend placement is a problem.

Per the suggestion of another post, I created a new csv file listing my categorical columns as names (as opposed to converting to factors).

This one, however, orders the Rating column alphabetically as oppossed to the original scale (1-5).

Shows graphic with good legend placement but incorrect order of Rating column

d3 <- 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))

Is someone able to assist?

Many thanks!

Jaap
  • 81,064
  • 34
  • 182
  • 193
N Gross
  • 41
  • 1
  • 2
  • 1
    have you tried your original `legend(legend = c("order1","order2",...))` – Nate Sep 29 '16 at 14:02
  • Cheers, Nathan - another colleague suggested using par (to expand margins) and args.legend=list (X = __, y = __), which worked a treat! – N Gross Oct 03 '16 at 07:44

0 Answers0