【问题标题】:R - Alternating colors in barchartR - 条形图中的交替颜色
【发布时间】:2018-08-22 22:09:11
【问题描述】:

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

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

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

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

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

干杯!

【问题讨论】:

    标签: r colors bar-chart alternating


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您所说的交替颜色是指您希望每个其他条都具有不同的颜色吗?

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

      结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-11
        • 2020-04-11
        • 2015-09-06
        • 2011-03-25
        • 2014-02-11
        • 1970-01-01
        • 2016-10-24
        • 1970-01-01
        相关资源
        最近更新 更多