R - 条形图中交替颜色

问题描述 投票:0回答:3

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

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

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

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("red", "green") 放入 fill 参数中,这也会导致错误“美学必须是长度 1 或与数据相同”。 因此,我尝试创建数据集长度的向量,但这也没有按我的计划工作。

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

干杯!

r colors bar-chart alternating
3个回答
3
投票

或者,使用带有“红色”、“绿色”向量的scale_fill_manual,该向量在数据帧的长度内重复

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


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

结果:


0
投票

作为 @caw5cv 答案的补充,您可以使用

discrete_scale()
创建一个简单的自定义色标,使其可移植并在管道中工作 (
%>%
)。

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

© www.soinside.com 2019 - 2024. All rights reserved.