我的表格是data.combined,结构如下:
'data.frame': 1309 obs. of 12 variables:
$ Survived: Factor w/ 3 levels "0","1","None": 1 2 2 2 1 1 1 1 2 2 ...
$ Pclass : Factor w/ 3 levels "1","2","3": 3 1 3 1 3 3 1 3 3 2 ...
$ Name : Factor w/ 1307 levels "Abbing, Mr. Anthony",..: 109 191 358 277 16 559 520 629 417 581 ...
$ Sex : num 2 1 1 1 2 2 2 2 1 1 ...
$ Age : num 22 38 26 35 35 NA 54 2 27 14 ...
$ SibSp : int 1 1 0 1 0 0 0 3 0 1 ...
$ Parch : int 0 0 0 0 0 0 0 1 2 0 ...
$ Ticket : Factor w/ 929 levels "110152","110413",..: 524 597 670 50 473 276 86 396 345 133 ...
$ Fare : num 7.25 71.28 7.92 53.1 8.05 ...
$ Cabin : Factor w/ 187 levels "","A10","A14",..: 1 83 1 57 1 1 131 1 1 1 ...
$ Embarked: Factor w/ 4 levels "","C","Q","S": 4 2 4 4 4 3 4 4 4 2 ...
$ Title : Factor w/ 4 levels "Master.","Miss.",..: 3 3 2 3 3 3 3 1 3 3 ...
我想绘制一个图表来反映Title和Survived之间的关系,按Pclass分类。我使用了以下代码:
ggplot(data.combined[1:891,], aes(x=Title, fill = Survived)) +
geom_histogram(binwidth = 0.5) +
facet_wrap(~Pclass) +
ggtitle ("Pclass") +
xlab("Title") +
ylab("Total count") +
labs(fill = "Survived")
然而,这会导致错误:Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"?
如果我将变量Title更改为numeric:data.combined$Title <- as.numeric(data.combined$Title)
,则代码可以正常工作,但图中的标签也是数字(下图)。请告诉我它为什么会发生以及如何解决它。感谢。
顺便说一句,我在Mac El Capital使用R 3.2.3。
图:x轴没有先生,而是x轴显示数值1,2,3,4
答案 0 :(得分:15)
总结上述评论的答案:
1 - 将geom_histogram(binwidth=0.5)
替换为geom_bar()
。但是这种方式不允许进行binwidth定制。
2 - 使用stat_count(width = 0.5)
代替geom_bar()
或geom_histogram(binwidth = 0.5)
即可解决此问题。
答案 1 :(得分:2)
What is the best real time plotting widget for wxPython?
extractTitle <- function(Name) {
Name <- as.character(Name)
if (length(grep("Miss.", Name)) > 0) {
return ("Miss.")
} else if (length(grep("Master.", Name)) > 0) {
return ("Master.")
} else if (length(grep("Mrs.", Name)) > 0) {
return ("Mrs.")
} else if (length(grep("Mr.", Name)) > 0) {
return ("Mr.")
} else {
return ("Other")
}
}
titles <- NULL
for (i in 1:nrow(data.combined)){
titles <- c(titles, extractTitle(data.combined[i, "Name"]))
}
data.combined$title <- as.factor(titles)
ggplot(data.combined[1:892,], aes(x = title, fill = Survived))+
geom_bar(width = 0.5) +
facet_wrap("Pclass")+
xlab("Pclass")+
ylab("total count")+
labs(fill = "Survived")
答案 2 :(得分:1)
如上所述,使用geom_bar()而不是geom_histogram,请参考下面给出的示例代码(我希望每个月的出生日期数据都有单独的图表):
ggplot(data = pf,aes(x=dob_day))+
geom_bar()+
scale_x_discrete(breaks = 1:31)+
facet_wrap(~dob_month,ncol = 3)
答案 3 :(得分:0)
我遇到了同样的问题,但以上解决方案均无效。然后我注意到我要用于直方图的数据框的列不是数字:
df$variable<- as.numeric(as.character(df$variable))
取自here