且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向格子条形图中的面板添加文本

更新时间:2023-12-04 10:04:46

这里的基本问题是如何在 lattice 中为堆叠的条形图添加标签.this question 中提供了答案,但由于链接的答案没有多个面板,我使用重新创建一个更简单的答案此处为基础 R:

The underlying question here is how to add labels to a stacked barchart in lattice. The answer is provided in this question, but since the linked answer doesn't have multiple panels, I recreate a simpler answer using base R here:

你必须修改面板功能如下:

You have to modify the panel function as follows:

  • 计算每个 y 值的 x 值的累积和
  • 这是一个经典的拆分、应用、组合问题.您可以为此使用 plyr (如链接答案中所示),或者,如我所示,使用 splitdo.call:
  • Calculate the cumulative sum of x values for each y value
  • This is a classic split, apply, combine problem. You can use plyr for this (as in the linked answer), or, as I illustrate, split and do.call:

xx <- do.call(c, unname(lapply(split(x, y), function(t)cumsum(t)-t/2)))

代码:

barchart( 1:10 ~ Petal.Width + Petal.Length | Species, 
          data = iris[c(1:10, 51:60, 101:110), ], 
          stack = TRUE,
          panel=function(x, y, ...) {
            panel.barchart(x, y, ...)
            xx <- do.call(c, unname(lapply(split(x, y), function(t)cumsum(t)-t/2)))
            ltext(xx, y=y, labels=x)
         }
)