fdel
fdel

Reputation: 15

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!

Upvotes: 0

Views: 4115

Answers (3)

FaniX
FaniX

Reputation: 355

As a supplement to @caw5cv's answer, you can create a simple custom color scale using discrete_scale() to make it portable and work in pipes (%>%).

library(ggplot2)
library(magrittr)

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(aes(x=month, y=n, fill=month)) +
  geom_bar(stat = "identity") +
  discrete_scale("fill", "custom", function(n){c("red","green")[1:n%%2+1]})

Alternating color bar chart

Upvotes: 0

caw5cv
caw5cv

Reputation: 721

Alternatively, use scale_fill_manual with a vector of "red","green" that repeats for the length of your data frame

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, fill=month)) +
geom_bar(stat = "identity") +
scale_fill_manual(values=rep(c("red","green"), ceiling(length(prodpermonth$month)/2))[1:length(prodpermonth$month)])

Result

Upvotes: 4

Simon Larsen
Simon Larsen

Reputation: 742

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

Upvotes: 1

Related Questions