Barplot忽略了colorpalette

时间:2015-05-22 20:24:16

标签: 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)

这是为什么?我设法使用ggplotreshape来制作图表,但它仍然困扰着我。

2 个答案:

答案 0 :(得分:4)

当你将Y看起来像矩阵的东西(即它有尺寸,或更具体地说是barplot()属性)时,它会根据{{为每个着色1}}。它在你的情况下做的是假设每个值是其类别中的第一个段。要将此简单数据框转换为矢量,请尝试dim ...

cols

答案 1 :(得分:3)

Barplot假设您使用堆积条,并且您只有一个类别。 如果您指定beside=TRUE,则不再是这种情况:

barplot(as.matrix(res), ylim=ticks, ylab="Mean Ratio", beside=TRUE,
        width=0.5, col=colors, xlab="Year", main="Mean ratio per year" )