【问题标题】:Create a histogram filled using another variable in ggplot在 ggplot 中创建使用另一个变量填充的直方图
【发布时间】:2017-01-16 09:30:52
【问题描述】:

我正在处理一个包含某些人年龄的数据集。我正在尝试使用 ggplot 为人们的年龄创建一个直方图,其中直方图条形的颜色应取决于一些预定义的年龄间隔。

例如,想象一个这样的数据集:

>X
   Age   Age2
   10    Under 14
   11    Under 14
   10    Under 14
   13    Under 14
   20    Between 15 and 25
   21    Between 15 and 25
   35    Above 25

我尝试过这样做:

ggplot(X, aes(x = Age)) + geom_histogram(aes(fill = Age2))

但它显示以下错误消息:

Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"?

我做错了什么?

【问题讨论】:

  • 从错误消息看来,x(年龄)不是连续的。尝试将 Age 更改为 as.numeric(Age)。
  • 或者as.numeric(as.character(Age)) 如果Age 是一个因素!!见str(X)

标签: r ggplot2 histogram fill


【解决方案1】:

使用 ggplot2 绘制,修正过大写。

age <-c(10,11,10,13,20,21,35)
age2<-c(rep("Under 14", times=4), rep("Between 15 and 25",times=2),"Above 25")
X<-as.data.frame(cbind(age,age2))
X$age<-as.numeric(age)
X
names(X)
summary(X)
p<- ggplot(X, aes(x = age))+
  geom_histogram(aes(fill = age2))
p

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多