简体   繁体   English

使用geom_bar在ggplot2中未显示的图

[英]Plots not showing in ggplot2 with geom_bar

I am trying to plot stacked bars using ggplot() and geom_bar() 我正在尝试使用ggplot()geom_bar()绘制堆积的条形图

Sample data (Titanic Kaggle question): 样本数据(Titanic Kaggle问题):

PassengerId   Survived   Age
          1          0    25
          2          1    20
          3          1    40
          4          0    10

I am trying to show stacked bars of survival and death for each age range (I have divided age into bins). 我正在尝试显示每个年龄段的生存和死亡的堆积图(我将年龄划分为垃圾箱)。 Plot is not visible when I execute the command. 执行命令时该图不可见。 and when I add print() function, I get the error as 当我添加print()函数时,出现错误

Error: No layers in plot 错误:情节中没有图层

Please tell if there is anything I am missing out here ? 请告诉我这里有什么我想念的吗?

breaks <- seq(min(train$Age), max(train$Age), 10)
p <- ggplot(train, aes(x=train$Age, y=length(train$PassengerId)), xlab = "age", ylab = "count", main = "survival", 
   fill = Survived + geom_bar(stat = "identity", bin = breaks))

print(p)

"train" is object in which I stored the data. “火车”是我存储数据的对象。

There are a few issues here: 这里有一些问题:

First you should remove the rows where age is NA, otherwise you can't create a sequence. 首先,您应该删除age为NA的行,否则无法创建序列。

train<-train[!is.na(train$Age),]

Then you should change your y value to train$Survived (why did you use length(train$PassengerId) ? - it doesn't display anything) The thing that @Pascal mentioned is also correct: You have to put + geom_bar(stat="identity", bin=breaks) outside. 然后,您应该将y值更改为train$Survived (为什么要使用length(train$PassengerId) ?-它什么都不显示)@Pascal提到的内容也是正确的:您必须输入+ geom_bar(stat="identity", bin=breaks)之外。 and you need to add the axes and title differently in ggplot. 并且您需要在ggplot中以不同的方式添加轴和标题。

This is the complete working code: 这是完整的工作代码:

train<-train[!is.na(train$Age),]

breaks <- seq(min(train$Age), max(train$Age), 10)
p <- ggplot(train, aes(x=train$Age, y=train$Survived), 
            fill = Survived)+ geom_bar(stat="identity", bin=breaks)
p <- p+labs(x="age", y="count")

p <- p+theme(plot.title= element_text("survival"))


print(p)

Results in this graph: 该图的结果: 在此处输入图片说明

apart from Pascal's hint, you may want to: 除了Pascal的提示,您可能还需要:

  • Use factors for colored column (Survived) 彩色柱的使用系数(尚存)
  • Use different geom_bar() and aes() params as suggested 根据建议使用不同的geom_bar()和aes()参数

Code: 码:

train <- data.frame(PassengerId = 1:4, Survived = factor(c(0,1,1,0)), Age = c(25, 20, 40, 10))
BIN.WIDTH <- 10
my.breaks <- seq(from = min(train$Age), to = max(train$Age) + BIN.WIDTH, by = BIN.WIDTH)
ggplot(train, aes(Age, fill = Survived)) + geom_bar(breaks = my.breaks)

Plot: 情节:

产生堆积图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM