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

More than 1 year has passed since last update.

【備忘録】棒グラフに個別データを重ねるやつ:geom_bar + geom_point + geom_line

Last updated at Posted at 2023-04-29

はじめに

最近実験心理学系の論文で流行っている棒グラフに個別データを載せるやつ。
完成形はこんな感じ↓
作り方の流れはgeom_barで棒グラフ, geom_pointgeom_lineで個人データを描きます。

Rplot.jpeg

目次

  1. 下準備
  2. 平均と標準偏差を出す
  3. グラフを描画
  4. グラフを保存
  5. 終わりに

下準備

今回使うデータ。
このデータはgeom_pointgeom_lineで使います。

id <- rep(seq(1, 10, 1), 4)
A <- rep(c(rep('a1', 10), rep('a2', 10)), 2)

a1 <- c(rnorm(10, mean=10, sd=5))
a2 <- c(rnorm(10, mean=25, sd=5))

original <- data.frame(id, A, Value  = c(a1, a2))


original

平均と標準偏差を出す

今回使うデータの平均と標準偏差を出します。
このデータはgeom_barで使います。

library(tidyverse)

SumData <- original %>% group_by(A) %>%
  dplyr::summarise(mean_Value = mean(Value), sd_Value = sd(Value))


SumData

グラフを描画

棒グラフはSumData、個別のプロットはoriginalから描画する。

Graph <- ggplot() +
  geom_bar(data = SumData, aes(x=A, y=mean_Value, fill = A), stat = "identity", alpha=0.7) +
  scale_fill_manual(values=c("gray60", "gray80")) +
  theme_classic() +
  geom_point(data = original, aes(x=A, y=Value, color = id), color="grey40")+
  geom_line(data = original, aes(x=A, y=Value, group = id), color="grey40") +
  geom_errorbar(data = SumData, aes(x=A, y=mean_Value, ymin=mean_Value-sd_Value, ymax=mean_Value+sd_Value), width=0.2) + 
  scale_y_continuous(breaks = c(0, 10, 20, 30, 40), limits = c(0, 40), expand = c( 0, 0) ) +
  ggtitle("title")+
  theme(text = element_text(size = 20))


plot(Graph)

グラフを保存

ggsave(file = "名前.png", plot = Graph)

終わりに

論文で報告する時は注釈に

「ラインプロットは個別値、エラーバーは標準偏差を表す」

を忘れずに。

0
0
2

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