1
votes

I'm trying to add a legend to a barplot. But am getting this error: Error in strwidth(legend, units = "user", cex = cex, font = text.font) : plot.new has not been called yet

I thought it might be my settings and the legend was pushed off of the graph - but I can't seem to get the legend to show up when I change my mar and par settings. And actually it doesn't appear that my oma and par settings change my graph at all (did I somehow reset the settings for good). I used dev.off() to reset to my default but that didn't work.

Thanks

Barplot

h<-c(4,12,3,36,4,3,2,10,35,41)

treat<-factor(rep(c(rep(c("one","two"),c(5,5))),1))

plot<-factor(c(rep(LETTERS[1:5],2)))

barchart(h~treat,data=df,groups=plot, ylim=c(0,60), ylab="Tips",
         col = gray.colors(6),scales=list(x=list(cex=0.8))) 


legend("top",legend=1:5)
1
barchart is a function from the Lattice package (which uses grid graphics) and legend is from base graphics. You can't easily combine them. Maybe this question will help you: stackoverflow.com/questions/23528122/…MrFlick
Why not base::barplot which you can set a legend?Parfait

1 Answers

1
votes

There is an auto.key parameter to barchart that will put a legend at the top by default:

barchart(h~treat,data=df,groups=plot, ylim=c(0,60), ylab="Tips",
         col = gray.colors(6),scales=list(x=list(cex=0.8)), auto.key=TRUE)

enter image description here

Since it is a lattice plotting routine, you would need to use print to see anything in a file graphics device:

 png(); print( barchart(h~treat,data=df,groups=plot, ylim=c(0,60), ylab="Tips",
    col = gray.colors(6),scales=list(x=list(cex=0.8)), auto.key=TRUE) ); dev.off()