2017-06-22 99 views
1

我想通過ggplot2生成的密度圖添加圖例,但不是添加示例標籤,我試圖用數字填充圖例。將平均值/模式值的自定義圖例添加到ggplot密度圖

library(ggplot2) 
library(modeest) 

set.seed(9) 
d1=as.data.frame(rnorm(1000,mean=0.33,sd=0.138)) 
names(d1)=c("value") 
mean_d1=mean(d1$value)     #Mean=0.33081 
mode_d1=mlv(d1$value,method="shorth")[1] #Mode=0.35191 

gg=ggplot(d1,aes(value)) 
gg + 
geom_density() 

這使得這樣的圖表: enter image description here

有沒有一種方法來添加包含平均值和模式值我已經計算出一個傳奇(嵌入在右上角)?

回答

0

可以使用annotate文本添加到ggplot

p + annotate("text", x = 0.6, y = 3, label = paste ("Mean ==", mean_d1), parse = TRUE) + 
    annotate("text", x = 0.6, y = 2.8, label = paste ("Mode ==", mode_d1), parse = TRUE) 

更新:

如果你想用這個情節不同再看看下面;

max_y <- ggplot_build(gg)$layout$panel_ranges[[1]]$y.range[2] 
max_x <- ggplot_build(gg)$layout$panel_ranges[[1]]$x.range[2] 

gg + 
    annotate("text", x = max_x * 0.85, y = max_y * 0.95, label = paste 
        ("Mean ==", round(mean_d1, digits=3)), parse = TRUE) + 
    annotate("text", x = max_x * 0.85, y = max_y * 0.9, label = paste 
        ("Mode ==", round(as.numeric(mode_d1), digits=3)), parse = TRUE) 
+0

謝謝Masound。這可以按原樣運行,但如果有解決方案可以:1)針對不同尺寸的圖(Y軸不會總是最多三個)進行縮放,並且2)自動繪製圖例框。我猜註釋也可以繪製形狀,但是當繪圖大小不同時存在同樣的問題。 – Michael

+0

閱讀此[線程](https://stackoverflow.com/questions/7705345/how-can-i-extract-plot-axes-ranges-for-a-ggplot2-object)。你可以從ggplot得到y和x lim,然後在註釋中設置x和y。 – Masoud