R - 条形图中的交替颜色

R - Alternating colors in barchart

我目前正在尝试编写一个闪亮的应用程序。我想创建一个对单选按钮具有反应性着色的条形图。

在尝试获取活性着色的代码之前,我尝试对其进行测试,以便了解如何编写代码。

现在我正在努力获得具有交替颜色的条形图。

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"))

此代码 returns 错误 "Continous value supplied to discrete scale"。

我试图将向量 c("red", "green") 赋给填充参数,这也会导致错误 "Aesthetics must be either length 1 or the same as the data"。 因此,我尝试创建一个数据集长度的向量,但这也没有按我的计划工作。

有没有更简单的方法在条形图中获取交替颜色?

干杯!

您所说的交替颜色是指您希望每隔一个条形都有不同的颜色吗?

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")

结果:

或者,将 scale_fill_manual 与 "red"、"green" 的向量一起使用,该向量会重复数据帧的长度

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)])