且构网

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

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

更新时间:2023-12-04 09:34:10

此处的基本问题是如何在lattice中的堆叠条形图中添加标签.答案在此问题中提供,但是由于链接的答案没有多个面板,因此我使用以下方法重新创建了一个更简单的答案在此处以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)
         }
)