Reputation: 155
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
Upvotes: 3
Views: 3984
Reputation: 263481
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)))
Upvotes: 3