2017-01-16 53 views
1

我正在處理包含某些人的年齡的數據集。我正在嘗試使用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"? 

我在做什麼錯?

+3

從好像X(年齡)的錯誤消息是不連續的。嘗試將Age更改爲as.numeric(年齡)。 – Haboryme

+2

或'as.numeric(as.character(年齡))'如果'年齡'是一個因素!!看'str(X)'。 – Axeman

回答

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 

sample output

相關問題