rcolorsbar-chartalternating

R - Alternating colors in barchart


i'm currently trying to write a shiny app. I want to create a barchart with reactive coloring to radiobuttons.

Before i try to get the code for the reactive coloring, i try to test it, so that i get an idea of how to compose the code.

Right now i'm struggling to get a barchart with alternating colors.

prodpermonth$month <- c("2008-11-01", "2008-12-01", "2009-01-01", "2009-02-01", "2009-03-01")
prodpermonth$n <- c(1769, 3248, 3257, 2923, 3260)

ggplot(prodpermonth, aes(x=prodmonth, y=n))+
geom_bar(stat = "identity", aes(fill = prodpermonth$prodmonth)) + 
scale_fill_manual(c("red", "green"))

This code returns an Error "Continous value supplied to discrete scale".

I tried to just give a vector c("red", "green") into the fill argument, which also results in an Error "Aesthetics must be either length 1 or the same as the data". Thus, i tried to create a vector of the length of the data set, but this also did not work as i planned.

Isn't there a simpler way to get alternating colors in a barchart?

Cheers!


Solution

  • By alternating colors do you mean, that you want every other bar to have a different color?

    library(ggplot2)
    
    prodpermonth <- data.frame(
      month = c("2008-11-01", "2008-12-01", "2009-01-01", "2009-02-01", "2009-03-01"),
      n = c(1769, 3248, 3257, 2923, 3260)
    )
    
    ggplot(prodpermonth, aes(x=month, y=n)) +
      geom_bar(stat = "identity", aes(fill = (as.numeric(month) %% 2 == 0))) +
      scale_fill_discrete(guide="none")
    

    Result:

    enter image description here