简体   繁体   English

ggplot geom_bar() 在绘图上填充不着色条

[英]ggplot geom_bar() fill not coloring bars on plot

Using the fill argument on geom_bar is not coloring the bars on my plot.在 geom_bar 上使用 fill 参数不会为我的绘图上的条着色。 I'm using the train.csv from the titanic data set here .我使用的是从泰坦尼克号数据集train.csv这里

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

I have tried moving the fill outside of the aes(), tried moving the aes up to the ggplot() function.我尝试将填充移动到 aes() 之外,尝试将 aes 移动到 ggplot() 函数。

This is the code I'm using on the Titanic Data set这是我在泰坦尼克号数据集上使用的代码

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

在此处输入图片说明

This is the code I'm using as a template which works fine on the ggplot built in diamonds data.这是我用作模板的代码,它在内置钻石数据的 ggplot 上运行良好。

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

在此处输入图片说明

I just keep getting grey bars with the geom_bar for Survived using Pclass as the fill.我只是不断地使用 geom_bar for Survived 获得灰色条,使用 Pclass 作为填充。

This is doing the trick for me:这对我有用:

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

在此处输入图片说明

You can try as.factor()你可以试试 as.factor()

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

Probably your variables is not factor可能你的变量不是因素

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

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