ggplot geom_bar()不填充图上的色条

时间:2019-03-28 14:25:06

标签: r ggplot2 kaggle

在geom_bar上使用fill参数不会使绘图上的条变色。我正在使用来自泰坦尼克号数据集here的train.csv。

passengers <- read.csv('../input/train.csv')

我尝试将填充移到aes()之外,尝试将aes移到ggplot()函数。

这是我在泰坦尼克号数据集上使用的代码

ggplot(data = passengers) + 
    geom_bar(mapping = aes(x=Survived, fill = Pclass))

enter image description here

这是我用作模板的代码,可以在内置于钻石数据的ggplot上正常工作。

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = cut))

enter image description here

我只是使用Pclass作为填充,使用geom_bar保持灰色条表示Survived。

2 个答案:

答案 0 :(得分:1)

这正在为我做窍门:

ggplot(data = passengers) + 
   geom_bar(mapping = aes(x=Survived, fill = as.character(Pclass)))

enter image description here

答案 1 :(得分:0)

您可以尝试as.factor()

ggplot(data = passengers) + 
geom_bar(mapping = aes(x=Survived, fill = as.factor(passengers$Pclass)))

可能您的变量不是因素

相关问题