Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Barplot ignores colorpalette

Tags:

r

I calculated means from different columns in different dataframes and put those into another dataframe to plot 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 uni-coloured barplot in yellow.

Same is true for

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

Why is this? I managed to do the graph with ggplot and reshape, but it still bothers me.

like image 996
nouse Avatar asked Mar 16 '23 23:03

nouse


1 Answers

When you hand barplot() something that looks like a matrix (i.e. it has dimensions, or more specifically a dim attribute), it colors each segment according to cols. What it is doing in your case is assuming 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")
like image 144
Ben Bolker Avatar answered Mar 27 '23 15:03

Ben Bolker