The fill in ggplot doesn't work

Hi everyone,
when running the following code

ggplot(sleepDay_merged, aes(total_sleep_records, fill = total_sleep_records)) + 
  geom_bar() 

The bins appear not colored. I've also tried using scale_fill_manual but it also doesn't work

Thanks

Interesting error. Somehow it doesn't like the numbers on the x-axis and for the fill.
It works well with A,B,C.
You can convert the numbers to characters, or add an "as.factor" to the fill line.


#this isn't working:
sleepDay_merged = tibble(
  "total_sleep_records" = c(rep(1, 300), 
                            rep(2, 100),
                            rep(3, 10)) )
ggplot(sleepDay_merged, 
       aes(total_sleep_records, fill = total_sleep_records)) + 
  geom_bar() 


# this works fine:
sleepDay_merged = tibble(
  "total_sleep_records" = c(rep("A", 300), 
                            rep("B", 100),
                            rep("C", 10)) )
ggplot(sleepDay_merged, 
       aes(total_sleep_records, fill = total_sleep_records)) + 
  geom_bar() 


#it works with a factor:
sleepDay_merged = tibble(
  "total_sleep_records" = c(rep(1, 300), 
                            rep(2, 100),
                            rep(3, 10)) )
ggplot(sleepDay_merged, 
       aes(x = total_sleep_records, 
           fill = as.factor(total_sleep_records))) + 
  geom_bar() 


#or when treating the number as character:
sleepDay_merged = tibble(
  "total_sleep_records" = c(rep("1", 300), 
                            rep("2", 100),
                            rep("3", 10)) )
ggplot(sleepDay_merged, 
       aes(total_sleep_records, fill = total_sleep_records)) + 
  geom_bar() 

1 Like

Thanks for your help Matthias. I've also found another solution on Slack

  sleepDay_merged, 
  aes(x = factor(total_sleep_records), fill = total_sleep_records)
) + 
  geom_bar()

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.