Skip to content

Instantly share code, notes, and snippets.

@tetlabo
Last active January 21, 2022 10:13
Show Gist options
  • Save tetlabo/890ddfef9f5cf1abc084eace4b34a5bc to your computer and use it in GitHub Desktop.
Save tetlabo/890ddfef9f5cf1abc084eace4b34a5bc to your computer and use it in GitHub Desktop.
ggpmiscパッケージでグラフィックス中に数式やモデルの評価指標を書き込むサンプル
# 線形回帰モデルに従う乱数を生成する
b <- 10
a <- 3
x <- rnorm(100, mean = 10, sd = 5)
e <- rnorm(100, sd = 10)
y <- (a * x) + b + e
lm_res <- lm(y ~ x)
library(ggplot2)
library(ggpmisc)
theme_set(theme_gray(base_size = 14))
df <- data.frame(x, y)
p1 <- ggplot(df, aes(x = x, y = y)) +
geom_point(size = 3) +
geom_smooth(method = "lm", formula = y ~ x) +
stat_poly_eq(formula = y ~ x,
eq.with.lhs = "italic(hat(y))~`=`~",
aes(label = paste(stat(eq.label), stat(adj.rr.label), sep = "~~~")),
parse = TRUE, size = 8)
p1 # visible space的なものが入る
ggsave(filename="ggpmisc_example01.png", p1)
# フォントを指定する例
p2 <- ggplot(df, aes(x = x, y = y)) +
geom_point(size = 3) +
geom_smooth(method = "lm", formula = y ~ x) +
stat_poly_eq(formula = y ~ x,
eq.with.lhs = "italic(hat(y))~`=`~",
aes(label = paste(stat(eq.label), stat(adj.rr.label), sep = "~~~")),
parse = TRUE, size = 8, family="IPAexGothic") # 「IPAexフォント」が必要です
p2 # フォントは変わるが、やはりvisible space的なものが入る
ggsave(filename="ggpmisc_example02.png", p2, device=ragg::agg_png) # raggパッケージが必要です
# 数式が正しく表示される例
# showtextパッケージでフォントを登録する
library(systemfonts)
library(showtext)
font_add("IPAexGothic", "ipaexg.ttf")
showtext_auto()
showtext_opts(dpi=240) # デフォルトのままでは目盛が極めて小さくなる
theme_set(theme_gray(base_size = 12, base_family="IPAexGothic"))
p3 <- ggplot(df, aes(x = x, y = y)) +
geom_point(size = 3) +
geom_smooth(method = "lm", formula = y ~ x) +
stat_poly_eq(formula = y ~ x,
eq.with.lhs = "italic(hat(y))~`=`~",
aes(label = paste(stat(eq.label), stat(adj.rr.label), sep = "~~~")),
parse = TRUE, size = 8, family="IPAexGothic") # 「IPAexフォント」が必要です
p3
ggsave(filename="ggpmisc_example03.png", p3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment