【问题标题】:R barplot different color for certain barsR barplot某些条的颜色不同
【发布时间】:2016-05-12 07:55:35
【问题描述】:

我正在处理 R 中的一个数据框,看起来像这样

test <- data.frame(c(1:4),c(5:8),c(9:12),c(13:16))
names(test) <- c("position","totalA","totalB","totalC")

不,我想创建一个堆叠的条形图,所有条形图都是黑色的,除了 1 个位置值,我想要 'totalA'、'totalB' 和 'totalC' 的不同颜色

这就是我创建条形图时所做的

test.melt <- melt(test, id = "position")
ggplot(test.melt, aes(x=position, y=value, fill=variable))+geom_bar(stat="identity")+scale_fill_manual(values=grey.colors(3))

所以现在所有条形都有条件着色,但只有当位置 == 2 时才会出现这种情况。其余所有条形都应该是黑色的。

编辑:我也需要这样做,同时只使用 barplot() 函数而不是 ggplot()。

我将它用于条形图

test.transposed <- setNames(data.frame(t(test[,-1])), test [,1])
barplot(as.matrix(test.transposed))

但是,我现在如何应用这种条件着色?

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以像这样在数据中准备您需要的组:

    test.melt$colour <- ifelse(test.melt$position == 2, 
                               as.character(test.melt$variable), "All other")
    library(ggplot2)
    ggplot(test.melt, aes(x=position, y=value, fill=colour))
      + geom_bar(stat="identity")
      + scale_fill_manual(values=c( "#000000", grey.colors(3)))
    

    这将产生:

    【讨论】:

    • 嗨,当我使用 barplot() 而不是 ggplot() 时,我也可以使用这种方法吗?
    • 我想是这样,我只想问一个新问题
    【解决方案2】:

    您可以在scale_fill_manual:scale_fill_manual(values = c("#000000", "#dddddd", "#000000"))中指定颜色

    ggplot(test.melt, aes(x=position, y=value, fill=variable))+geom_bar(stat="identity") + scale_fill_manual(values = c("#000000", "#dddddd", "#000000"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 2018-04-08
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多