【问题标题】:Including custom text in legend of plot在图例中包含自定义文本
【发布时间】:2012-05-01 22:59:29
【问题描述】:

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

> 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 中自动实现这一点?

【问题讨论】:

    标签: r plot


    【解决方案1】:

    这解决了 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))
    

    这是从an answer on Rhelp that I posted in 2010 中提取的,该an answer on Rhelp that I posted in 2010 将解决方案的策略归因于 Gabor Grothendieck 和 Thomas Lumley 2005 年的交流。

    【讨论】:

    • 感谢指向sapply(foo, as.expression) 的指针。我想我以前也在 SO 上使用过那个人,现在我想起来了。
    【解决方案2】:

    这非常接近:

    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)

    如果不阅读?legend,我的函数addMyLegend() 的其余部分应该是相当不言自明的。请注意,您可以通过addMyLegend() 中的... 将任何参数传递给legend()

    【讨论】:

    • 谁能解释为什么 plotmath 在这里不起作用?我在做傻事吗?
    • 谢谢,在我的示例中,V2 是频率,V1 是值。 V1 并不总是以 1 开头。因此平均值应该是 MEAN=1.66 而不是 3574.5。
    • @neversaint 哎呀,对不起。会修复的。
    • 注意你是如何得到平均值和标准差的(mean(1:6) 不是 1.66 等)
    猜你喜欢
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2011-03-04
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多