在格子条形图中向面板添加文本 [英] Adding text to panels in lattice barchart

查看:98
本文介绍了在格子条形图中向面板添加文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将标签添加到具有多个面板的格子条形图中.我最终会看到太多标签(每个标签都在每个面板中).

I try to add labels to bars in a lattice barchart with multiple panels. I end up with way too many labels (every label is in every panel).

这是我的代码:

library(lattice)
data(iris)

barchart(seq(1,50) ~ Petal.Width + Petal.Length | Species, data = iris, stack = TRUE,
         panel=function(x, y, ...) {
               panel.barchart(x, y, ...);
               ltext(x=iris$Petal.Width/2, y=y, labels=iris$Petal.Width, cex = 0.5);
               ltext(x=iris$Petal.Width + iris$Petal.Length/2, y=y, labels=iris$Petal.Width, cex = 0.5);
         }
)

我该怎么做?

奖励问题:
除了无法正常工作外,我认为我的代码也不太高效(尤其是seq(1,50)Petal.Width + Petal.Length).有更好的方法吗?

Bonus question:
Beside it does not work as expected, I think my code is not too efficient (especially seq(1,50) and Petal.Width + Petal.Length). Is there a better way?

预先感谢您!

推荐答案

此处的基本问题是如何在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)
         }
)

这篇关于在格子条形图中向面板添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆