繁体   English   中英

在情节图例中包括自定义文本

[英]Including custom text in legend of plot

假设我有一个看起来像这样的数据。

> print(dat)
V1    V2
1  1 11613
2  2  6517
3  3  2442
4  4   687
5  5   159
6  6    29

# note that V2 is the frequency and V1 does not always start with 1. 


> plot(dat,main=title,type="h")
   # legend()??

现在,我要做的是绘制直方图,并将均值和标准差包括在图例中。 在上面的示例中,标准偏差等于0.87,平均值等于1.66。

如何在R中自动实现?

在此处输入图片说明 这解决了Gavin注意的图例创建问题。

require(Hmisc) 
myMean <- wtd.mean(dat$V1, dat$V2)
mySD <- sqrt(wtd.var(dat$V1, dat$V2))
plot(dat,main="title",type="h")

L= list( bquote(Mean== .(myMean)), bquote(SD== .(mySD) ) ) 
legend('topright', legend=sapply(L, as.expression))

这是从我在2010年发布的关于Rhelp的答案中得出的,该答案将解决方案的策略归因于2005年Gabor Grothendieck与Thomas Lumley之间的交流。

这非常接近:

dat <- data.frame(V1 = 1:6, V2 = c(11613, 6517, 2442, 687, 159, 29))

addMyLegend <- function(data, where = "topright", digits = 3, ...) {
    MEAN <- round(mean(data), digits = digits)
    SD <- round(sd(data), digits = digits)
    legend(where, legend = list(bquote(Mean == .(MEAN)), 
                                bquote(SD == .(SD))),
           ...)
}

plot(dat, type = "h")
addMyLegend(dat$V1, digits = 2, bty = "n")

这使

自定义图例

我不确定为什么plotmath代码没有显示==和排版= ...将不得不调查这一点。

要了解正在发生的事情,请阅读?bquote ,其中解释了该表达式可用于用动态数据替换表达式的组件。 包装在.( )都将替换为在表达式的包装部分中命名的对象的值。 因此foo == .(bar)将寻找一个命名对象bar和插入的值bar到表达。 如果bar包含1.3则应用bquote(foo == .(bar))之后的结果将类似于expression(foo == 1.3)

我的函数addMyLegend()的其余部分应该很容易解释,如果不读?legend 请注意,您可以通过addMyLegend()...将任何参数传递给legend() addMyLegend()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM