R - 条形图中的交替颜色

时间:2018-03-14 11:34:10

标签: r colors bar-chart alternating

我正在尝试编写一个闪亮的应用程序。我想创建一个带有反应性着色的条形图。

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

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

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

此代码返回错误“提供给离散比例的连续值”。

我试图在向填充参数中给出一个向量c(“红色”,“绿色”),这也会导致错误“美学必须是长度1或与数据相同”。 因此,我试图创建一个数据集长度的向量,但这也没有像我计划的那样工作。

是否有更简单的方法在条形图中获得交替的颜色?

干杯!

2 个答案:

答案 0 :(得分:2)

或者,使用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)])

Result

答案 1 :(得分:1)

通过交替颜色,你的意思是,你希望每个其他的酒吧都有不同的颜色吗?

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

结果:

enter image description here

相关问题