1

I am trying to plot a simple bar plot; however, every time I try, I get a gray style plot. I read the answer here Change bar plot colour in geom_bar with ggplot2 in r and followed the steps explained there, but I still get "gray color". I am not sure, maybe I am missing detail in my code. Here is my code:

out<- table(sub_select$yq, sub_select$AEoutcome)  
out<-cbind(out, Precentage = out[,2]/rowSums(out))
out <- as.data.frame(out)

the result is in this form:

        FALSE TRUE Precentage
2014 Q4   880   46 0.04967603
2015 Q1  1815   77 0.04069767
2015 Q2  1677   73 0.04171429
2015 Q3  1191   50 0.04029009
2015 Q4   555   13 0.02288732

then I run the following code:

x <- rownames(out)
ggplot(data=out, aes(x=x, y=Precentage), fill = x) +
  geom_bar(stat="identity", position=position_dodge()) +
  geom_text(aes(label=round(Precentage, digit=3)), vjust=1.6, color="black", position = position_dodge(0.9),size=3.5)

and this will return a graph in gray color. Any suggestions on how to fix this? Thanks

Ross_you
  • 881
  • 5
  • 22

2 Answers2

1

Try this. Set x directly in your dataframe. It is better. And also pass the fill option inside aes() as that was the main issue. Here the code:

library(ggplot2)
#Code
ggplot(data=out, aes(x=x, y=Precentage, fill = x)) +
  geom_bar(stat="identity", position=position_dodge()) +
  geom_text(aes(label=round(Precentage, digit=3)),
            vjust=1.6, color="black",
            position = position_dodge(0.9),size=3.5)

Output:

enter image description here

Some data used:

#Data
out <- structure(list(`FALSE` = c(880L, 1815L, 1677L, 1191L, 555L), 
    `TRUE` = c(46L, 77L, 73L, 50L, 13L), Precentage = c(0.04967603, 
    0.04069767, 0.04171429, 0.04029009, 0.02288732), x = c("2014 Q4", 
    "2015 Q1", "2015 Q2", "2015 Q3", "2015 Q4")), row.names = c(NA, 
-5L), class = "data.frame")
Duck
  • 39,058
  • 13
  • 42
  • 84
  • Thanks, Duck, so you moved the fill function into "aes", right? ggplot is so confusing, I can never figure out an easy way to understand it. Thanks for your help – Ross_you Oct 23 '20 at 00:32
  • 1
    @Roozbeh_you Yeah that is right, when you have a variable, try to use it inside `aes()` otherwise you will get all gray! – Duck Oct 23 '20 at 00:33
  • @Roozbeh_you It should work now in your code. I hope that helped you ! – Duck Oct 23 '20 at 00:34
1

You need to move fill = x into aes(), like this:

x <- rownames(out)
ggplot(data=out, aes(x=x, y=Precentage, fill = x)) +
  geom_bar(stat="identity", position=position_dodge()) +
  geom_text(aes(label=round(Precentage, digit=3)), vjust=1.6, color="black", position = position_dodge(0.9),size=3.5)

Placing fill outside aes() sets a constant value for everything being plotted. This is defaulting to grey as x is not a color name or hex code.

semaphorism
  • 836
  • 3
  • 13