r - 条形图忽略调色板

标签 r

我计算了不同数据框中不同列的均值,并将它们放入另一个数据框中以绘制它们。从这个代码

 res <- structure(list(`2012` = 6.86537485268066, 
                       `2013` = 5.91282899425944, 
    `2014` = 4.45070377934188),
     .Names = c("2012", "2013", "2014"),    
     row.names = c(NA, -1L), class = "data.frame")
colors<- c("yellow", "red", "green")
ticks <- c(0,8)
barplot(as.matrix(res), ylim=ticks, ylab="Mean Ratio", 
        width=0.5, col=colors, xlab="Year", main="Mean ratio per year")

我得到一个单色的黄色条形图。

同样适用于
myMat<-matrix(runif(3), ncol=3) 
barplot(myMat, col=colors)

为什么是这样?我设法用 ggplot 绘制了图表和 reshape ,但它仍然困扰着我。

最佳答案

当你手barplot()看起来像矩阵的东西(即它有维度,或者更具体地说是 dim 属性),它根据 cols 为每个段着色.它在您的情况下所做的是假设每个值都是其类别中的第一个段。要将这个简单的数据框转换为向量,请尝试 unlist() ...

barplot(unlist(res), ylim=ticks, ylab="Mean Ratio", 
        width=0.5, col=colors, xlab="Year",
        main="Mean ratio per year")

关于r - 条形图忽略调色板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30405329/

相关文章:

r - 比 strsplit() 在 R 中将字符串分成两部分的内存效率更高的方法

减小 EPS 格式的绘图大小

r - 如何在 R 中的函数内部使用 dplyr/magrittr 的管道?

r - 为什么 as.POSIXct 使我的时间增加 1 小时?

r - 如何向现有的 Aspell 词典中添加更多单词?

r - fastPOSIXct 相当于将非 UTC 转换为 UTC

r - 如何自动将逻辑因素转换为标记良好的因素?

r - 使用 tryCatch 在出错时跳到循环的下一个值?

r - 分解 R 数据框

regex - 如何使用 R 解析 html 字符串?