Home > Mobile >  Whats wrong with ggplot bar chart fill?
Whats wrong with ggplot bar chart fill?

Time:11-25

I'm trying to create a ggplot bar chart, and to create different colored fills for some bars. I copied from somewhere the code, but with my data it just deosnt work.

Here is the code:

df <- data.frame(cat  = c( 0,  1,  2,  3, 4),
                 perc = c(10, 20, 30, 40, 0),
                 mark = c( 0,  0,  0,  1, 0))

library(ggplot2)

ggplot(df)   
  aes(x = cat, fill = mark, weight = perc)  
  geom_bar() 

But the result is a colorless chart, with this warning message:

The following aesthetics were dropped during statistical transformation: fill
ℹ This can happen when ggplot fails to infer the correct grouping structure in the data.
ℹ Did you forget to specify a `group` aesthetic or to convert a numerical variable into a factor? 

What am I doing wrong?

CodePudding user response:

The issue is that geom_bar uses stat_count by default, so it simply counts up the number of rows at each value of cat. This summary doesn't know what to do with the fill = mark part of your mapping, since there could be multiple values for mark in each category. In your case this isn't obvious because there is only one value for fill at each value of cat, but the same principle applies; if you are using a grouped summary function then you cannot have a row-wise fill variable.

My guess is that you are looking for geom_col

df <- data.frame(cat  = c( 0,  1,  2,  3, 4),
                 perc = c(10, 20, 30, 40, 0),
                 mark = c( 0,  0,  0,  1, 0))

library(ggplot2)

ggplot(df)   
  aes(x = cat, fill = mark, y = perc)  
  geom_col() 

Created on 2022-11-24 with reprex v2.0.2

  • Related