[英]Issues making a histogram with ggplot
我想 plot 一個簡單的身高、體重和年齡直方圖,使用 ggplot 在 x 軸上表示年齡
首先,我構建不同的措施並制作 dataframe:
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)
問題是直方圖一直像條形圖一樣顯示,變量年齡看起來像一個謹慎的變量而不是連續變量,並且沒有為每個條形圖指定分配的年份:
我也收到此錯誤消息:
警告消息:“忽略未知參數:binwidth、bins、pad”
我試過使用scale_x_continuous
, scale_y_continuous
,沒有它們,只有scale_x_continuous
,我檢查了變量 age 是否是數字並且仍然存在相同的問題。 也許我錯過了一件非常簡單的事情,我不確定,但我真的很感激任何幫助。
提前致謝
如果您想要按height
顯示age
的直方圖,則必須將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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.