!関数をプロットする 乱数でデータを発生させてグラフを描くばかりでなく、関数を直接描画する方法がある。 ```{r} ggplot() + xlim(-4, 4) + geom_function(fun = dnorm, args = list(mean = 1, sd = 1), color = "blue") + geom_function(fun = pnorm, args = list(mean = 1, sd = 1), color = "red") + stat_function(fun = dnorm, args = list(mean = 0, sd = 0.5), n = 25, geom = "point") ``` geom_function()とstat_function()はともに関数と引数をそれぞれ、fun=...()とargs=list(...)で指定するところは同じで、stat_function()はグラフの要素をgeom=引数で指定できるところが異なる。 !関数グラフをファセット表示する 関数をグラフにする際に、パラメタの組み合わせをいろいろと変えて、並べてみたいことがある。 例えば、ベータ関数のalpha, betaの組み合わせを作るなど。 geom_function()に渡すデータはIgnoreされるのでひと工夫必要。r-wakalang@KDさんに教わった。 expand_grid(alpha = c(10, 20), beta = c(15, 30)) |> rowwise() |> mutate( data = list( tibble( x = seq(0, 1, length.out = 1000L), d = dbeta(x = x, shape1 = alpha, shape2 = beta) ) ) ) |> unnest(data) |> ggplot() + aes(x = x, y = d) + geom_path() + facet_grid(alpha ~ beta, labeller = "label_both") :参考: * https://ggplot2.tidyverse.org/reference/geom_function.html !関数の変数に項目名を渡す 関数には変数を通じて値を渡すことができるが、その値が項目名である場合には、関数内でそれを明示する。 my_plot <- function(df, var){ df %>% ggplot(aes(x=date)) + geom_line(aes(y={{var}})) } my_plot(tsla, close) my_plotというグラフを描画する関数にデータフレームdfと項目名varを与える。 varにはcloseという項目名が与えられるので、{{var}}として変数の中の項目名を得る。 :参考: * https://www.r-bloggers.com/2022/02/how-to-write-functions-with-ggplot/?fbclid=IwAR2jjRzbhLUbTYW9UrktEA8sr-Ih8FoFZ0Bywe6NnI628A4a6PmGY4CrhJY