简体   繁体   中英

ggplot geom_bar() fill not coloring bars on plot

Using the fill argument on geom_bar is not coloring the bars on my plot. I'm using the train.csv from the titanic data set here .

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.

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(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.

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()

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

Probably your variables is not factor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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