使用 ggplot 制作直方图的问题

Issues making a histogram with ggplot

我想绘制一个简单的身高、体重和年龄直方图,使用 ggplot 在 x 轴上显示年龄

首先我构建不同的度量并制作数据框:

age <- seq(from=10, to=21)
age

height <- c(147,152,157,160,163,172,177,180,183,184,185,185)
height

weight <- c(47,54,61,63,65,66,69,72,79,81,82,83)
weight

df <- data.frame(age,height,weight, stringsAsFactors = F)
df$age <- as.numeric(df$age)


df$class[df$age <14] = "child"
df$class[df$age <=17 & df$age>=14] = "teen"
df$class[df$age >17] = "adult"
df

然后我做了一个简单的直方图:

library(ggplot2)

ggplot(df, aes(x=age, y=height))+geom_histogram(fill="white",color="black",stat="identity",bins=12)

问题是直方图一直像条形图一样显示,变量 age 看起来像一个离散变量而不是连续变量,并且没有为每个条指定分配的年份:

而且我还收到此错误消息:

Warning message: "Ignoring unknown parameters: binwidth, bins, pad"

我试过 scale_x_continuousscale_y_continuous,没有它们,只有 scale_x_continuous,我检查了变量 age 是否是数字,但仍然有同样的问题。也许我错过了一件非常简单的事情,我不确定,但我真的很感激任何帮助。

提前致谢

如果您想要 heightage 直方图,您必须将 weight = height 作为 geom_histogram 美学而不是 y 坐标传递。
我还以更简单的方式重做了数据集,使用 cut 定义(不需要的)class 向量。

age <- 10:21
height <- c(147,152,157,160,163,172,177,180,183,184,185,185)
weight <- c(47,54,61,63,65,66,69,72,79,81,82,83)
class <- cut(age, 
             breaks = c(0, 14, 17, Inf), 
             labels = c("child", "teen", "adult"))
df <- data.frame(age, height, weight, class, stringsAsFactors = F)

ggplot(df, aes(age)) +
  geom_histogram(aes(weight = height),
                 fill = "white", 
                 color = "black", 
                 bins = 12)