Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add legend in a histogram (lattice)

I am new to R programming and I would like to make a histogram about sex and the correspondent jobs.

The problem I have is that I can't add a legend in the diagram.

Also, I would like on the top of every bar to add the frequency number.

Could you help me please ?

library(lattice)
histogram(~ job | sex, col=rainbow(7), main="", xlab = "", ylab="(%)")

P.S. I am trying with legend function but I get this error:

Error in strwidth(legend, units = "user", cex = cex) : plot.new has not been called yet

like image 722
user494766 Avatar asked Dec 29 '25 03:12

user494766


1 Answers

I am guessing that you have been reading intro material that taught you to use attach. Try to unlearn that. It's a bad habit if you want to use lattice. (And a generally bad habit all around for writing code.) Assuming you have these two variables in a dataframe, dfrm in long format, then try this:

library(lattice)
histogram(~ job | sex, data=dfrm, auto.key=TRUE, 
                      col=rainbow(7),  main="", xlab = "", ylab="(%)")

The legend function will not mix well with lattice, since it is base graphics. You could try, but the coordinate system for placement is very different.

I tested a variant of the above with the singer dataset and it did not succeed. This example works after adding a Freq column to the singer dataset:

singer$Freq <- ave(singer$height, singer$voice.part, FUN=length)
barchart(Freq ~ height, groups = voice.part,
        data = singer, 
        stack = TRUE, horizontal=FALSE,
   par.settings=list(superpose.polygon=list(col=rainbow(8))), 
   auto.key=list(x = .6, y = .7, corner = c(0, 0)))
like image 61
IRTFM Avatar answered Dec 30 '25 17:12

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!