所以我這個問題已經有一段時間了,我還沒有找到解決方案。每當我想標記感興趣的引數時,例如中心趨勢(平均值、中位數等),我創建一條垂直和/或水平線并使用注釋進行標記。但是,我無法同時使用 LaTeX 和非硬編碼值。MRE如下所示:
data <- data.frame(stat = rnorm(1000))
plot <-
ggplot(data, aes(x = stat))
geom_histogram(aes(y=..density..), fill="aquamarine", color="black")
geom_density(color="black", size=1)
geom_vline(xintercept = 0, color = "blue", linetype="dashed", size = 1)
annotate("text", x=-0.2, y=0.2,
label=paste0("Mean = ", round(mean(data$stat), 4)),
angle=90, size=7, color="black")
plot
參見此處的圖:https ://i.stack.imgur.com/QzojQ.png
在上面的示例中,我生成了一些隨機正常資料,將其保存到資料框并繪制它。我添加了一條對應于資料平均值的垂直虛線,然后通過注釋對其進行標記。但是請注意,我明確寫Mean在標簽中,因為 LaTeX 運算子不起作用并且隨機字母對我來說并不理想。
我發現的一個解決方案是使用expression而不是paste0標記時,如下所示:
data <- data.frame(stat = rnorm(1000))
plot <-
ggplot(data, aes(x = stat))
geom_histogram(aes(y=..density..), fill="aquamarine", color="black")
geom_density(color="black", size=1)
geom_vline(xintercept = 0, color = "blue", linetype="dashed", size = 1)
annotate("text", x=-0.25, y=0.2, label = expression(mu ~ "= -0.0403"),
angle=90, size = 7, color = "black")
plot
參見此處的圖:https ://i.stack.imgur.com/rnW5i.png
這使我們能夠在繪圖中顯示 LaTeX 字符,例如在我們的例子中是 $\mu$。但現在的缺點是我必須在運算式欄位中硬編碼平均值。這并不理想,我不想這樣做。我希望能夠執行以下操作,但這不起作用:
annotate("text", x=-0.25, y=0.2,
label = expression(mu ~ round(mean(data$stat), 4)),
angle=90, size = 7, color = "black")
我一直無法找到解決方案,因此非常感謝任何幫助。
uj5u.com熱心網友回復:
解決此問題的一種選擇是將運算式創建為字串,而不是使用expression并添加parse=TRUE到annotate:
library(ggplot2)
set.seed(123)
data <- data.frame(stat = rnorm(1000))
ggplot(data, aes(x = stat))
geom_histogram(aes(y = after_stat(density)), fill = "aquamarine", color = "black")
geom_density(color = "black", size = 1)
geom_vline(xintercept = 0, color = "blue", linetype = "dashed", size = 1)
annotate("text",
x = -0.2, y = 0.2,
label = paste0("mu ==", round(mean(data$stat), 4)),
angle = 90, size = 7, color = "black", parse = TRUE
)
#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
#> ? Please use `linewidth` instead.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/533302.html
標籤:rggplot2
