3

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

1 Answer 1

3

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)))
1
  • @user49766 If it's what you wanted, then you should "accept" or "check" the answer.
    – IRTFM
    Mar 27, 2011 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.