1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ggplot2; 棒グラフとエラーバーを一気通貫にプロットする

Last updated at Posted at 2025-02-10

エラーバー付き棒グラフを一気に書きたい

RT-PCRなどの結果をFigureにするとき、エラーバー付きの棒グラフを書くと思います。
少し調べると、書き方を紹介する記事がいくつか出てきますが、データの平均とSDを、dplyr::summarise()とgroup_by()を使ってまず算出し、その結果をもとにプロットしているもので、二度手間感を感じてしまいました。

GPTに聞いた結果

そこでchatGPTに聞いてみると以下のお返事。

まずは、例となるdataframeの準備です。

library(ggplot2)
# 仮のデータフレームを作成
set.seed(123)
df <- data.frame(
  group = rep(LETTERS[1:3], each = 10),
  value = c(rnorm(10, mean = 5, sd = 1),
            rnorm(10, mean = 7, sd = 1),
            rnorm(10, mean = 6, sd = 1))
)

ここからが本題です。

# stat_summary() を利用して直接プロット
ggplot(df, aes(x = group, y = value)) +
  stat_summary(fun = mean, geom = "bar", fill = "lightblue", color = "black") +
  stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.2) +
  theme_minimal()

プロットはこちら。

image.png

私自身、見様見真似でggplot2を使っている分際ですが、geom_hogehoge()にくらべてstat_summary()には慣れていません。
調べてもあまり日本語での情報が出てきづらいのも一つの原因かもしれません。
stat_summary()をもっと使いこなせたら、得なのでしょうね…。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?