Reputation: 3471
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.
Upvotes: 4
Views: 64
Reputation: 3862
Barplot assumes that you use stacked bars, and you have only one category.
If you specify beside=TRUE
, that 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" )
Upvotes: 3
Reputation: 226577
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")
Upvotes: 4