在直方图(格子)中添加图例

发布于 2024-10-27 13:59:43 字数 349 浏览 0 评论 0原文

我是 R 编程新手,我想制作一个关于性别和相应工作的直方图。

我遇到的问题是我无法在图表中添加图例。

另外,我想在每个栏的顶部添加频率数字。

你能帮我一下吗?

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

PS 我正在尝试使用图例功能,但收到此错误:

strwidth(图例,单位 =“用户”,cex = cex)中的错误: plot.new尚未被调用

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

踏月而来 2024-11-03 13:59:43

我猜您一直在阅读教您使用 attach 的介绍材料。尝试忘记这一点。如果你想使用lattice,这是一个坏习惯。 (这对于编写代码来说是一个普遍的坏习惯。)假设您在数据帧中有这两个变量,dfrm采用长格式,然后尝试以下操作:

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

legend函数将与点阵不能很好地混合,因为它是基础图形。你可以尝试一下,但是放置的坐标系非常不同。

我使用 singer 数据集测试了上述内容的变体,但没有成功。此示例在向歌手数据集添加 Freq 列后起作用:

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

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)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文