Barplot ignores colorpalette

I calculated the tools from different columns in different data frames and put them in a different data frame to build them. From this code

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

I get a single color barcode in yellow.

The same is true for

myMat<-matrix(runif(3), ncol=3) 
barplot(myMat, col=colors)

Why is this? I managed to make a schedule with ggplotand reshape, but it still bothers me.

+4
source share
2 answers

When you pass barplot()in what looks like a matrix (i.e. has dimensions or, more specifically, an attribute dim), it colors each segment according to cols. What it does in your case suggests that each of the values ​​is the first segment in its category. To convert this simple data frame to a vector, try unlist()...

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

Barplot assumes you are using stacked columns and you only have one category. If you specify beside=TRUE, this is no longer the case:

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

Source: https://habr.com/ru/post/1589506/


All Articles