在 ggplot 中创建一个使用另一个变量填充的直方图
Create a histogram filled using another variable in ggplot
我正在处理一个包含某些人年龄的数据集。我正在尝试使用 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"?
我做错了什么?
使用 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
我正在处理一个包含某些人年龄的数据集。我正在尝试使用 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"?
我做错了什么?
使用 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