LoginSignup
2
7

More than 3 years have passed since last update.

R tips 可視化に使えるライブラリ ggplot2

Last updated at Posted at 2020-11-19

記事の目的

この記事では、可視化によく使用されるライブラリであるggplot2の基本的な使い方を説明します。

目次

No. 目次 説明
1 使用するライブラリとデータ ggplot2 / iris
2 基本的な可視化 geom_〇〇
3 グラフを見やすく! labs, xlim, ylim
4 グラフに色を付ける fill, color
5 複数のグラフを1つのグラフに表示 geom_〇〇+ geom_〇〇
6 複数のグラフを同時に表示 gridExtra / grid.arrange

1. 使用するライブラリとデータ

library(dplyr)
library(ggplot2)
iris %>% sample_n(5)

image.png

2. 基本的な可視化 (geom_〇〇)

1次元 (ヒストグラム、棒グラフ)

iris %>% ggplot(aes(x=Sepal.Length)) + geom_histogram()
iris %>% ggplot(aes(x=Species)) + geom_bar()

image.png

2次元 (棒グラフ、散布図、折れ線グラフ)

NULL %>% ggplot(aes(x=c(1,2,3), y=c(10,20,30))) + geom_bar(stat="identity")
iris %>% ggplot(aes(x=Sepal.Length, y=Sepal.Width)) + geom_point()
iris %>% ggplot(aes(x=Sepal.Length, y=Sepal.Width)) + geom_line()

image.png

2次元 -グループ別比較- (箱ひげ図、バイオリンプロット)

iris %>% ggplot(aes(x=Species, y=Sepal.Length)) + geom_boxplot()
iris %>% ggplot(aes(x=Species, y=Sepal.Length)) + geom_violin()

image.png

3. グラフを見やすく! (labs, xlim, ylim)

グラフに名前を付ける (labs)

iris %>% ggplot(aes(x=Species)) + geom_bar() +
  labs(x="種類", y="個体数", title="種類別の個体数")

image.png

グラフの範囲を設定する (xlim, ylim)

iris %>% ggplot(aes(x=Sepal.Length, y=Sepal.Width)) + geom_point() +
  xlim(4,8) + ylim(1,5)

image.png

4. グラフに色を付ける (fill, color)

1次元 (fill)

iris %>% ggplot(aes(x=Sepal.Length)) + geom_histogram(fill="red")
iris %>% ggplot(aes(x=Sepal.Length)) + geom_histogram(aes(fill=Species))

image.png

2次元 (color)

iris %>% ggplot(aes(x=Sepal.Length, y=Sepal.Width)) + geom_point(color="blue")
iris %>% ggplot(aes(x=Sepal.Length, y=Sepal.Width)) + geom_line(color="green")
iris %>% ggplot(aes(x=Sepal.Length, y=Sepal.Width)) + geom_point(aes(color=Species))

image.png

グラフを薄くする (alpha)

iris %>% ggplot(aes(x=Sepal.Length)) + geom_histogram(aes(fill=Species, alpha=0.5))

image.png

5. 複数のグラフを1つのグラフに表示 (geom_〇〇+geom_〇〇)

xが共通の場合

iris %>% ggplot(aes(x=Sepal.Length)) + geom_point(aes(y=Sepal.Width)) +
  geom_line(aes(y=Sepal.Width)) + 
  geom_histogram(alpha=0.5)

image.png

バラバラのデータの場合

iris %>% ggplot() + geom_point(aes(x=Sepal.Length, y=Sepal.Width)) +
  geom_line(aes(x=Petal.Length, y=Petal.Width))

image.png

6. 複数のグラフを同時に表示 (gridExtra / grid.arrange)

今までに表示した複数のグラフは、この関数を使用していました。

library(gridExtra)
p1 <- iris %>% ggplot(aes(x=Sepal.Length)) + geom_histogram()
p2 <- iris %>% ggplot(aes(x=Species)) + geom_bar()
grid.arrange(p1, p2, nrow=1)

image.png

◯SNS
・youtube
https://youtube.com/channel/UCFDyXEywtNhdtwqC3GAkYuA

・Twitter
https://twitter.com/Dken_ta

2
7
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
2
7