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

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

问题描述

我尝试在具有多个面板的格状条形图中向条形添加标签.我最终得到了太多标签(每个标签都在每个面板中).

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 中为堆叠的条形图添加标签.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)
         }
)

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

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