[英]ggplot add variable to legend without including in plot (when using alpha)
[英]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.