简体   繁体   中英

Including custom text in legend of plot

Suppose I have a data that looks like this.

> 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()??

Now what I want to do is to plot histogram, and have the mean and standard deviation included as the legend. In the above example the standard deviation equals 0.87 and the mean eauals 1.66.

How can I achieve that automatically in R?

在此处输入图片说明 This solves the problem with legend creation that Gavin notices.

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))

This was pulled from an answer on Rhelp that I posted in 2010 that attributed the strategy for the solution to a 2005 exchange between Gabor Grothendieck and Thomas Lumley.

This gets pretty close:

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")

Which gives

自定义图例

I'm not sure why the plotmath code is not displaying the == and a typeset = ... Will have to look into that.

To see what is going on read ?bquote which explains that it can be used to replace components of an expression with dynamic data. Anything wrapped in .( ) will be replaced by the value of the object named in the wrapped part of the expression. Thus foo == .(bar) will look for an object named bar and insert the value of bar into the expression. If bar contained 1.3 then the result after applying bquote(foo == .(bar)) would be similar to expression(foo == 1.3) .

The rest of my function addMyLegend() should be fairly self explanatory, if not read ?legend . Note you can pass on any arguments to legend() via the ... in addMyLegend() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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