Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在绘图图例中包含自定义文本_R_Plot - Fatal编程技术网

R 在绘图图例中包含自定义文本

R 在绘图图例中包含自定义文本,r,plot,R,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()?? 现在我要做的是绘制柱状图,并得到平均值 图例中

假设我有这样一个数据

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

这一点非常接近:

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

dat这非常接近:

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

dat这解决了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))
require(Hmisc)

myMean这解决了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))
require(Hmisc)

有人能解释为什么plotmath不在这里工作吗?我在做傻事吗?谢谢,在我的例子中,V2是频率,V1是值。V1并不总是以1开头。因此,平均值应该是平均值=1.66,而不是3574.5。@neversaint哎呀,对不起。将修复。请注意如何获得平均值和sd(
mean(1:6)
不是1.66等)以及计算sd:有人能解释为什么plotmath不在这里工作吗?我在做傻事吗?谢谢,在我的例子中,V2是频率,V1是值。V1并不总是以1开头。因此,平均值应该是平均值=1.66,而不是3574.5。@neversaint哎呀,对不起。将修复。请注意如何获得平均值和sd(
mean(1:6)
不是1.66等)以及计算sd:感谢指向
sapply(foo,as.expression)
的指针。我想我以前也用过这个词,所以现在我想起来了。谢谢你给我的
sapply(foo,as.expression)
。我想我以前也用过那个人,所以现在我想起来了。