如何在 ggplot2 中实际使用图层而不是 geom_histogram() 绘制直方图?

问题描述 投票:0回答:1

我试图使用layer()命令来创建一个简单的直方图而不是geom_histogram(),但遇到了问题。最终,R找不到一个叫做直方图的几何图形!我在这里缺少什么?

df <-data.frame(
sex <- rep(c("M","F"), each =50),
height <- round(c(rnorm(50, mean = 5.5, sd = .5), rnorm(50, mean = 4.8, sd = .8)),1)
)
df

library(ggplot2)
p <- ggplot()
p+ layer(data = df, geom = "histogram", mapping = aes(x=height, fill  = sex))
p+ layer(data = df, geom = "histogram", mapping = aes(x=height, fill  = sex), stat = "count")
p+ layer(data = df, geom = "histogram", mapping = aes(x=height, fill  = sex), stat = "count", position = "identity")


> >> p+ layer(data = df, geom = "histogram", mapping = aes(x=height, fill  = sex))
Error:
> ! Can't create layer without a stat.
> Run `rlang::last_trace()` to see where the error occurred.


> > p+ layer(data = df, geom = "histogram", mapping = aes(x=height, fill  = sex), stat = "count")
> Error:
> ! Can't create layer without a position.
> Run `rlang::last_trace()` to see where the error occurred.


> > p+ layer(data = df, geom = "histogram", mapping = aes(x=height, fill  = sex), stat = "count", > position = "identity")
> Error:
> ! Can't find geom called "histogram"
> Run `rlang::last_trace()` to see where the error occurred.

r ggplot2 histogram
1个回答
0
投票

恕我直言,可以通过明确说明对于

geom=
只能使用具有相应
Geom
原型子类的几何对象的短名称来改进文档,即
geom_histogram
基本上是
geom_bar
 的简写stat="bin"
对应的
Geom
原型子类是
GeomBar
。因此,要使用
layer()
绘制“直方图”,请使用
geom="bar"
geom=GeomBar

set.seed(123)

df <- data.frame(
  sex <- rep(c("M", "F"), each = 50),
  height <- round(c(rnorm(50, mean = 5.5, sd = .5), rnorm(50, mean = 4.8, sd = .8)), 1)
)

library(ggplot2)

p <- ggplot()

p +
  layer(
    data = df, geom = "bar", mapping = aes(x = height, fill = sex),
    stat = "count", position = "identity"
  )

另请注意,

geom_histogram
使用
stat="bin"
:


p +
  layer(
    data = df, geom = "bar", mapping = aes(x = height, fill = sex),
    stat = "bin", position = "identity"
  )
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

© www.soinside.com 2019 - 2024. All rights reserved.