我正在嘗試在 ggplot 中制作一個帶標簽的散點圖,標簽的細節讓我很不舒服。基本上,除其他外,我想用 R^2 和 Mean Bias 注釋我的 facet_wrapped 2-panel ggplot。值得注意的是,我想用適當的單位標記平均偏差。
我的資料的簡單版本可能如下所示:
library(tidyverse)
Demo_Df <- tibble(Modeled = rnorm(50,0,1), Observed = rnorm(50, 0.5, 1),
Scheme = c(rep("Scheme1", 25), rep("Scheme2", 25)))
Demo_Annotation <- tibble(r.squared = c(0.589, 0.573), Mean_Bias = c(-2.038, -1.049), Scheme = c("Scheme1", "Scheme2"))
Demo_Scatter <- Demo_Df %>%
ggplot(aes(x = Observed, y = Modeled, color = Scheme))
geom_point(size = 1.5)
facet_wrap(~Scheme)
theme_tufte()
xlab(expression(paste("Observed Aerosol (", mu, "g m" ^ "-3", ")"), sep = ""))
ylab(expression(paste("Modeled Aerosol (", mu, "g m" ^ "-3", ")"), sep = ""))
ylim(-3, 4)
theme(legend.position = "none")
Demo_Labeled <- Demo_Scatter
geom_text(data = Demo_Annotation, aes(-2, 3,
label = paste(
"R2 = ", sprintf("%.2f", signif(r.squared, 3)), "\n",
"Mean Bias = ", sprintf("%.2f", signif(Mean_Bias, 3))
)),
size = 5, hjust = 0, color = "black")
這產生了幾乎正確的數字,但我希望 R2 有一個上標 2,我需要在“平均偏差 =”標簽的末尾添加每立方米微克 (ug/m3),因為它在 x 上和 y 軸。
迄今為止,我在這方面完全失敗了。我找不到支持多行facet_wrap、變數輸入和 AND 運算式的解決方案。必須有辦法做到這一點。請幫幫我,tidyverse 大神們!
uj5u.com熱心網友回復:
實作您想要的結果的一種選擇是通過多個geom_text圖層為您添加多條線。要將標簽決議為數學符號,請添加parse=TRUE到geom_text. 最后,我將標簽添加到您的注釋 df 中,我在其中使用?plotmath了數學符號。
library(tidyverse)
library(ggthemes)
Demo_Annotation <- Demo_Annotation %>%
mutate(r.squared = paste0("R^{2} == ", sprintf("%.2f", signif(r.squared, 3))),
Mean_Bias = paste0("Mean~Bias == ", sprintf("%.2f", signif(Mean_Bias, 3)), "~mu*g~m^{-3}"))
Demo_Scatter
geom_text(data = Demo_Annotation, aes(x = -2, y = 4, label = r.squared),
size = 5, hjust = 0, color = "black", parse = TRUE, family = "serif")
geom_text(data = Demo_Annotation, aes(x = -2, y = 3.5, label = Mean_Bias),
size = 5, hjust = 0, color = "black", parse = TRUE, family = "serif")

資料
set.seed(42)
Demo_Df <- tibble(Modeled = rnorm(50,0,1), Observed = rnorm(50, 0.5, 1),
Scheme = c(rep("Scheme1", 25), rep("Scheme2", 25)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338237.html
