条形图未显示每个类别

Bar plot not showing every category

我有一个名为 sim_1[[2]] 的列表,如下所示:

## [[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
....................

下面是我生成条形图的代码:

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

我应该有 m1 到 m9 模型,但我的条形图只显示了其中的 4 个。为什么会这样?

最简单的选择是转换为 factor,并将 levels 指定为完整的列名,这样如果我们没有该特定列的任何频率计数,它将 return 0而不是不在图片中

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

配合OP的barplot代码,可以

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

-输出

数据

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