目的:グラフの凡例の順序をマニュアルでいじる

Rの凡例の順序はデフォルトだとアルファベット順になっています。 この記事では、この凡例の順序をマニュアルでいじるやり方をメモしていきます。

libraryの読み込み

library(tidyverse)
## ─ Attaching packages ──────────────────── tidyverse 1.3.0 ─
## ✓ ggplot2 3.3.3     ✓ purrr   0.3.4
## ✓ tibble  3.1.0     ✓ dplyr   1.0.5
## ✓ tidyr   1.1.3     ✓ stringr 1.4.0
## ✓ readr   1.4.0     ✓ forcats 0.5.1
## ─ Conflicts ───────────────────── tidyverse_conflicts() ─
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(reshape2)
## 
## Attaching package: 'reshape2'
## The following object is masked from 'package:tidyr':
## 
##     smiths

今回用いるデータ

今回は以下に示してあるsample.csvというcsvファイルに入っているデータを使います。 このcsvファイルはエクセル上で適当に数字を打って作りました。

read.csv("sample.csv")->yama #csvファイルを読み込み、yamaという名前で格納。
yama
##    Genotype Time Curvature
## 1        WT    0         0
## 2        WT    0         0
## 3        WT    0         0
## 4        WT    0         0
## 5        WT    0         0
## 6        WT    2        20
## 7        WT    2        21
## 8        WT    2        22
## 9        WT    2        25
## 10       WT    2        18
## 11       WT    4        40
## 12       WT    4        42
## 13       WT    4        41
## 14       WT    4        47
## 15       WT    4        49
## 16       WT    8        80
## 17       WT    8        75
## 18       WT    8        90
## 19       WT    8        88
## 20       WT    8        82
## 21   mutant    0         0
## 22   mutant    0         0
## 23   mutant    0         0
## 24   mutant    0         0
## 25   mutant    0         0
## 26   mutant    2        10
## 27   mutant    2         5
## 28   mutant    2         4
## 29   mutant    2        19
## 30   mutant    2        12
## 31   mutant    4        16
## 32   mutant    4        20
## 33   mutant    4        23
## 34   mutant    4        25
## 35   mutant    4        20
## 36   mutant    8        29
## 37   mutant    8        20
## 38   mutant    8        22
## 39   mutant    8        21
## 40   mutant    8        15

データの加工

上記のデータから、WTとmutantのデータの平均値とsd, seを時間ごとに求めます。 そのデータをgroup_time_mean_sdに格納します。

group_time_mean_sd <-yama %>% 
  group_by(Genotype, Time) %>% 
  summarize(mean = mean(Curvature), sd = sd(Curvature), se = sd/sqrt(5)) 
## `summarise()` has grouped output by 'Genotype'. You can override using the `.groups` argument.
group_time_mean_sd
## # A tibble: 8 x 5
## # Groups:   Genotype [2]
##   Genotype  Time  mean    sd    se
##   <chr>    <int> <dbl> <dbl> <dbl>
## 1 mutant       0   0    0     0   
## 2 mutant       2  10    6.04  2.70
## 3 mutant       4  20.8  3.42  1.53
## 4 mutant       8  21.4  5.03  2.25
## 5 WT           0   0    0     0   
## 6 WT           2  21.2  2.59  1.16
## 7 WT           4  43.8  3.96  1.77
## 8 WT           8  83    6.08  2.72

デフォルトでの折れ線グラフの出力

group_time_mean_sdから、WTとmutantのCurvatureの経時変化を折れ線グラフにプロットします。 デフォルトのプロットだとこんな感じで、mutant, WTの順に凡例が出力されます。

g <- ggplot(group_time_mean_sd, aes(x = Time,#x軸をTimeに
                      y = mean,
                      shape = Genotype,
                      group = Genotype,
                      linetype = Genotype,
                      color = Genotype) #y軸をCurvatureに
                      )
g <- g + scale_x_continuous(breaks = seq(0,8,2))#y軸の値を(最小値,最大値,間隔)で指定
g <- g + geom_line()
g <- g + geom_point(size = 4)
errors <- aes(ymax = mean + se, ymin = mean - se)
g <- g + geom_errorbar(errors, width = 0.1)
g <- g + theme_classic()#背景をclassicに
g <- g + theme(legend.position = c(0.2,0.8),#legendの位置指定
               legend.title = element_blank(),#legendタイトルをなしに
               axis.title.x = element_text(size = 18, family = "Arial"),  
               axis.title.y = element_text(size = 18, family = "Arial"), 
               axis.text.x = element_text(size = 15, colour = 1, family = "Arial"), 
               axis.text.y = element_text(size = 15, colour = 1, family = "Arial"),
               )

g <- g + xlab("Time (h)")
g 
m_WT

凡例の順番をいじった折れ線グラフの出力

以下のコードが凡例の順番をいじるのに効いてます。

group_time_mean_sd$Genotype <- factor(group_time_mean_sd$Genotype, 
                                      levels=c("WT", "mutant"))

それを含めてプロットすると凡例がWT, mutantの順になります。

group_time_mean_sd$Genotype <- factor(group_time_mean_sd$Genotype, 
                                      levels=c("WT", "mutant"))
g <- ggplot(group_time_mean_sd, aes(x = Time,#x軸をTimeに
                      y = mean,
                      shape = Genotype,
                      group = Genotype,
                      linetype = Genotype,
                      color = Genotype) #y軸をCurvatureに
                      )
g <- g + scale_x_continuous(breaks = seq(0,8,2))#y軸の値を(最小値,最大値,間隔)で指定
g <- g + geom_line()
g <- g + geom_point(size = 4)
errors <- aes(ymax = mean + se, ymin = mean - se)
g <- g + geom_errorbar(errors, width = 0.1)
g <- g + theme_classic()#背景をclassicに
g <- g + theme(legend.position = c(0.2,0.8),#legendの位置指定
               legend.title = element_blank(),#legendタイトルをなしに
               axis.title.x = element_text(size = 18, family = "Arial"),  
               axis.title.y = element_text(size = 18, family = "Arial"), 
               axis.text.x = element_text(size = 15, colour = 1, family = "Arial"), 
               axis.text.y = element_text(size = 15, colour = 1, family = "Arial"),
               )
g <- g + xlab("Time (h)")
g
WT_m