Bar plot not showing every category

Viewed 181

I have a list called sim_1[[2]] that looks like this:

## [[1]]
##         m1    m2    m3     m4     m5     m6     m7     m8     m9
## 1    2.516 1.642 1.113 1.0799 1.0844 0.9667 0.9671 0.9943 0.9961
## 2    2.617 1.647 1.173 1.1399 1.1201 0.9958 0.9950 1.0193 1.0183
## 3    2.594 1.587 1.167 1.1264 1.1265 0.9987 1.0062 1.0086 1.0144
## 4    2.625 1.707 1.203 1.1574 1.1565 1.0491 1.0473 1.0474 1.0480
## 5    2.584 1.572 1.117 1.0696 1.0672 0.9866 0.9879 0.9838 0.9834
....................

And below is my code for generating barplot:

barplot(table(colnames(sim_1[[2]])[apply(sim_1[[2]], 1, which.min)]),
  xlab = "Models",
  ylab = "Frequency",
  main = expression("Frequency of chosen model for"~sigma~"="~1),
  col = "lightsteelblue",
  border = "darkred"
  )

Output of barplot

I should have m1 to m9 models but my barplot is only showing 4 of them. Why is this happening?

1 Answers

The easiest option is to convert to factor with levels specified as the full column names so that if we don't have any frequency count for that particular column, it will return 0 instead of being absent from the picture

nm1 <- colnames(sim_1[[2]])[apply(sim_1[[2]], 1, which.min)]
table(factor(nm1, levels = colnames(sim_1[[2]])))

With the OP's barplot code, it can be

barplot(table(factor(nm1, levels = colnames(sim_1[[2]]))),
  xlab = "Models",
  ylab = "Frequency",
  main = expression("Frequency of chosen model for"~sigma~"="~1),
  col = "lightsteelblue",
  border = "darkred"
  )

-ouput

enter image description here

data

sim_1 <- list(NULL, structure(list(m1 = c(2.516, 2.617, 2.594, 2.625, 
2.584), m2 = c(1.642, 1.647, 1.587, 1.707, 1.572), m3 = c(1.113, 
1.173, 1.167, 1.203, 1.117), m4 = c(1.0799, 1.1399, 1.1264, 1.1574, 
1.0696), m5 = c(1.0844, 1.1201, 1.1265, 1.1565, 1.0672), m6 = c(0.9667, 
0.9958, 0.9987, 1.0491, 0.9866), m7 = c(0.9671, 0.995, 1.0062, 
1.0473, 0.9879), m8 = c(0.9943, 1.0193, 1.0086, 1.0474, 0.9838
), m9 = c(0.9961, 1.0183, 1.0144, 1.048, 0.9834)), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5")))
Related