1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ggplotを用いた幾何平均とその信頼区間のプロット

1
Last updated at Posted at 2022-12-23

はじめに

これは、Rに関するSlackのチーム「r-wakalang」で自分で回答した質問を記事にしたものです。
Slackが90日でアクセス不能になるため忘れそうなので、記事にしていきます。

「r-wakalang」については下記記事をご参照ください
https://qiita.com/uri/items/5583e91bb5301ed5a4ba

問題

status,scoreの2列で成り立つデータセットにおいて、横軸にA,B,C,Dを並べ縦軸にpointを蜂群図としてプロットし、おなじ図の中にscoreの幾何平均とその95%CIを入れ込みたい。

解法

## 必要な関数定義
gmean <- function(Arr) { ##幾何平均を返す
  return(exp(mean(log(Arr))))
} 

gmean_cl_normal<- function(Arr) { ##幾何平均と信頼区間を返す
  return(data.frame(
    y = gmean(Arr),
    ymin = gmean(Arr) - 1.96 * exp(sd(log(Arr))),
    ymax = gmean(Arr) + 1.96 * exp(sd(log(Arr)))
  ))
}
## データ準備
df <-tibble(
  status=c(rep("A",25),rep("B",25),rep("C",25),rep("D",25)),
  score = c(sample(seq(1,5),50,replace = TRUE),sample(seq(6,10),50,replace = TRUE))
)
## プロット
df %>%
  ggplot2::ggplot(aes(x = status, y = score)) +
  ggbeeswarm::geom_beeswarm()+
  ggplot2::stat_summary(fun = gmean, geom = "point", color = "red") +
  ggplot2::stat_summary(fun.data = gmean_cl_normal, geom = "errorbar", color = "red")

image.png

ポイント

stat_summaryで自作関数を適応することで 解決ができる。
プロットを指定するgeomによって、適応する関数の形が変わる。値が1つしか要求されないされない場合は、fun=(function)でいいが、3つ(ymin, y, and ymax)要求される場合はfunfun.min, fun, fun.maxのどちらかを用いる。違いは下に引用する

fun.data
A function that is given the complete data and should return a data frame with variables ymin, y, and ymax.
fun.min, fun, fun.max
Alternatively, supply three individual functions that are each passed a vector of values and should return a single number.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?