ggplot2のチートシートをirisデータで試してみた

# はじめに

[ggplot2](https://ggplot2.tidyverse.org/) の [Cheat Sheet](https://github.com/rstudio/cheatsheets/blob/master/data-visualization-2.1.pdf) を`iris`データの例で試してみました。

CheatSheet：https://github.com/rstudio/cheatsheets/blob/master/data-visualization-2.1.pdf


**目次**

- [データの準備](#データの準備)
- [Geoms](#geoms)
    - [GRAPHICAL PRIMITIVES](#graphical-primitives) 
        - [geom_blank()](#geom_blank)
        - [geom_curve()](#geom_curve)
        - [geom_path()](#geom_path)
        - [geom_polygon()](#geom_polygon)
        - [geom_rect()](#geom_rect)
        - [geom_ribbon()](#geom_ribbon)
    - [LINE SEGMENTS](#line-segments)
        - [geom_abline()](#geom_abline)
        - [geom_hline(), geom_vline()](#geom_hline-geom_vline)
        - [geom_segment()](#geom_segment)
        - [geom_spoke()](#geom_spoke)
    - [ONE VARIABLE](#one-variable)
        - [continuous](#continuous)
            - [geom_area(stat = "bin")](#geom_areastat--bin)
            - [geom_density()](#geom_density)
            - [geom_dotplot()](#geom_dotplot)
            - [geom_freqpoly()](#geom_freqpoly)
            - [geom_histogram()](#geom_histogram)
            - [geom_qq()](#geom_qq)
        - [descrete](#descrete)
            - [geom_bar()](#geom_bar)
    - [TWO VARIABLES](#two-variables)
        - [continuous x, continuous y](#continuous-x-continuous-y)
            - [geom_label()](#geom_label)
            - [geom_jitter()](#geom_jitter)
            - [geom_point()](#geom_point)
            - [geom_quantile()](#geom_quantile)
            - [geom_rug()](#geom_rug)
            - [geom_smooth()](#geom_smooth)
            - [geom_text()](#geom_text)
        - [discrete x, continuous y](#discrete-x-continuous-y)
            - [geom_col()](#geom_col)
            - [geom_boxplot()](#geom_boxplot)
            - [geom_dotplot()](#geom_dotplot)
            - [geom_violin()](#geom_violin)
        - [discrete x, discrete y](#discrete-x-discrete-y)
            - [geom_count()](#geom_count)
        - [continuous bivariate distribution](#continuous-bivariate-distribution)
            - [geom_bin2d()](#geom_bin2d)
            - [geom_density2d()](#geom_density2d)
            - [geom_hex()](#geom_hex)
        - [continuous function](#continuous-function)
            - [geom_area()](#geom_area)
            - [geom_line()](#geom_line)
            - [geom_step()](#geom_step)
        - [visualizing error](#visualizing-error)
            - [geom_crossbar()](#geom_crossbar)
            - [geom_errorbar()](#geom_errorbar)
            - [geom_linerange()](#geom_linerange)
            - [geom_pointrange()](#geom_pointrange)
        - [maps](#maps)
            - [geom_map()](#geom_map)
    - [THREE VARIABLES](#three-variables)
        - [geom_contour()](#geom_contour)
        - [geom_raster()](#geom_raster)
        - [geom_tile()](#geom_tile)
- [Scales](#scales)
    - [Scales](#scales-1)
        - [scale_fill_manual()](#scale_fill_manual)
    - [GENERAL PURPOSE SCALES](#general-purpose-scales)
    - [X & Y LOCATION SCALES](#x-&-y-location-scales)
        - [scale_x_log10()](#scale_x_log10)
        - [scale_x_reverse()](#scale_x_reverse)
        - [scale_x_sqrt()](#scale_x_sqrt)
    - [COLOR AND FILL SCALES (DISCRETE)](#color-and-fill-scales-discrete)
        - [scale_fill_brewer()](#scale_fill_brewer)
        - [scale_fill_grey()](#scale_fill_grey)
    - [COLOR AND FILL SCALES (CONTINUOUS)](#color-and-fill-scales-continuous)
        - [scale_fill_distiller()](#scale_fill_distiller)
        - [scale_fill_gradient()](#scale_fill_gradient)
        - [scale_fill_gradient2()](#scale_fill_gradient2)
        - [scale_fill_gradientn()](#scale_fill_gradientn)
    - [SHAPE AND SIZE SCALES](#shape-and-size-scales)
        - [scale_shape(), scale_size()](#scale_shape-scale_size)
        - [scale_shape_manual()](#scale_shape_manual)
        - [scale_radius()](#scale_radius)
        - [scale_size_area()](#scale_size_area)
- [Coordinate Systems](#coordinate-systems)
    - [coord_cartesian()](#coord_cartesian)
    - [coord_fixed()](#coord_fixed)
    - [coord_flip()](#coord_flip)
    - [coord_polar()](#coord_polar)
    - [coord_trans()](#coord_trans)
    - [coord_quickmap(), coord_map()](#coord_quickmap-coord_map)
- [Position Adjustments](#position-adjustments)
- [Themes](#themes)
- [Faceting](#faceting)
    - [facet_grid()](#facet_grid)
    - [facet_wrap()](#facet_wrap)
- [Labels](#labels)
    - [labs()](#labs)
    - [annotate()](#annotate)
- [Legends](#legends)
    - [theme()](#theme)
    - [guides()](#guides)
    - [scale_\*_\*()](#scale__)
- [Zooming](#zooming)
    - [coord_cartesian(xlim = , ylim = )](#coord_cartesianxlim---ylim--)
- [Stats](#stats)
- [参考文献](#参考文献)


# データの準備

共通して使うデータを先に用意しておきます。

- `iris_id`：`iris`データに行番号（1～150）"id"とSpeciesごとの行番号（1～50）"id2"を振ったもの
- `iris_head3`：`iris_id`からSpeciesごとに先頭3行を取り出したもの（id2が1～3）
- `iris_head5`：`iris_id`からSpeciesごとに先頭5行を取り出したもの（id2が1～5）
- `iris_head10`：`iris_id`からSpeciesごとに先頭10行を取り出したもの（id2が1～10）
- `iris_round`：`iris`のSepal.Length～Petal.Widthをそれぞれ丸めて整数化して因子型にしたもの
- `iris_summary`：`iris`のSpeciesごとにSepal.Lengthのmeanとsdを集計したもの

```R:R
library(tidyverse)

iris_id <- iris %>% as_tibble() %>% 
  rowid_to_column("id") %>% 
  group_by(Species) %>% 
  mutate(id2 = row_number(id)) %>% relocate(id, id2) %>% 
  ungroup() %>% print()
# # A tibble: 150 x 7
#       id   id2 Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#    <int> <int>        <dbl>       <dbl>        <dbl>       <dbl> <fct>  
#  1     1     1          5.1         3.5          1.4         0.2 setosa 
#  2     2     2          4.9         3            1.4         0.2 setosa 
#  3     3     3          4.7         3.2          1.3         0.2 setosa 
#  4     4     4          4.6         3.1          1.5         0.2 setosa 
#  5     5     5          5           3.6          1.4         0.2 setosa 
#  6     6     6          5.4         3.9          1.7         0.4 setosa 
#  7     7     7          4.6         3.4          1.4         0.3 setosa 
#  8     8     8          5           3.4          1.5         0.2 setosa 
#  9     9     9          4.4         2.9          1.4         0.2 setosa 
# 10    10    10          4.9         3.1          1.5         0.1 setosa 
# # ... with 140 more rows

iris_head3 <- iris_id %>% 
  filter(id2 %in% 1:3) %>% print()
# # A tibble: 9 x 7
#      id   id2 Sepal.Length Sepal.Width Petal.Length Petal.Width Species   
#   <int> <int>        <dbl>       <dbl>        <dbl>       <dbl> <fct>     
# 1     1     1          5.1         3.5          1.4         0.2 setosa    
# 2     2     2          4.9         3            1.4         0.2 setosa    
# 3     3     3          4.7         3.2          1.3         0.2 setosa    
# 4    51     1          7           3.2          4.7         1.4 versicolor
# 5    52     2          6.4         3.2          4.5         1.5 versicolor
# 6    53     3          6.9         3.1          4.9         1.5 versicolor
# 7   101     1          6.3         3.3          6           2.5 virginica 
# 8   102     2          5.8         2.7          5.1         1.9 virginica 
# 9   103     3          7.1         3            5.9         2.1 virginica 

iris_head5 <- iris_id %>% 
  filter(id2 %in% 1:5)

iris_head10 <- iris_id %>% 
  filter(id2 %in% 1:10)

iris_round <- iris %>% as_tibble() %>% 
  rename(sl = Sepal.Length, sw = Sepal.Width,
         pl = Petal.Length, pw = Petal.Width) %>% 
  mutate(across(1:4, .fn = ~factor(round(.)), .names = "round_{col}")) %>% print()
# # A tibble: 150 x 9
#       sl    sw    pl    pw Species round_sl round_sw round_pl round_pw
#    <dbl> <dbl> <dbl> <dbl> <fct>   <fct>    <fct>    <fct>    <fct>   
#  1   5.1   3.5   1.4   0.2 setosa  5        4        1        0       
#  2   4.9   3     1.4   0.2 setosa  5        3        1        0       
#  3   4.7   3.2   1.3   0.2 setosa  5        3        1        0       
#  4   4.6   3.1   1.5   0.2 setosa  5        3        2        0       
#  5   5     3.6   1.4   0.2 setosa  5        4        1        0       
#  6   5.4   3.9   1.7   0.4 setosa  5        4        2        0       
#  7   4.6   3.4   1.4   0.3 setosa  5        3        1        0       
#  8   5     3.4   1.5   0.2 setosa  5        3        2        0       
#  9   4.4   2.9   1.4   0.2 setosa  4        3        1        0       
# 10   4.9   3.1   1.5   0.1 setosa  5        3        2        0       
# # ... with 140 more rows

iris_summary <- iris %>%
  group_by(Species) %>%
  summarise(mean = mean(Sepal.Length), sd = sd(Sepal.Length)) %>%
  ungroup() %>% print()
# # A tibble: 3 x 3
#   Species     mean    sd
#   <fct>      <dbl> <dbl>
# 1 setosa      5.01 0.352
# 2 versicolor  5.94 0.516
# 3 virginica   6.59 0.636
```


# Geoms

## GRAPHICAL PRIMITIVES

#### geom_blank()

（グラフなしで）座標軸のみ描きます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_blank()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3e54acd0-9edc-bbe9-6712-f19bc8daf9b8.png)


#### geom_curve()

`geom_segment()`が点(x, y)と点(xend, yend)を結ぶ線分を描くのに対して、`geom_curve()`は点(x, y)と点(xend, yend)を結ぶカーブを描きます。

- `geom_segment()`：点(x, y)と点(xend, yend)を結ぶ線分を描く
- `geom_curve()`　：点(x, y)と点(xend, yend)を結ぶカーブを描く

```R:R
ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_curve(aes(xend = Sepal.Length + 0.5, yend = Sepal.Width + 0.1))
ggplot(data = iris_head3) +
  geom_curve(aes(x = Sepal.Length, y = Sepal.Width,
                 xend = Sepal.Length + 0.5, yend = Sepal.Width + 0.1,
                 color = Species))

ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_point(aes(x = Sepal.Length + 0.5, y = Sepal.Width + 0.1), shape = 3) +
  geom_curve(aes(xend = Sepal.Length + 0.5, yend = Sepal.Width + 0.1))
ggplot(data = iris_head3, aes(color = Species)) +
  geom_point(aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(x = Sepal.Length + 0.5, y = Sepal.Width + 0.1), shape = 3) +
  geom_curve(aes(x = Sepal.Length, y = Sepal.Width,
                 xend = Sepal.Length + 0.5, yend = Sepal.Width + 0.1))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/06a794c4-455f-56d4-b52a-e01f6e2e238d.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/8a35cb0b-5761-b5a2-c795-f925a7620f6a.png)

`curvature`でカーブの曲率を変えられます（デフォルトは0.5）。

```R:R
ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = 1, color = 1) +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = 2, color = 2) +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = 3, color = 3) +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = 4, color = 4) +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = 0, color = 5)

ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = -1, color = 1) +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = -2, color = 2) +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = -3, color = 3) +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = -4, color = 4) +
  geom_curve(aes(xend = Sepal.Length+0.1,
                 yend = Sepal.Width+0.1), curvature = 0, color = 5)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/1061bd95-c7f5-d26b-0e7b-9f9a5aa47118.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/93494c7b-bea0-7030-6eeb-e9a0ec6c2640.png)


#### geom_path()

x座標, y座標に指定した点列$(x_i, y_i)$を順に結ぶパスを描きます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_path()

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_path() +
  geom_point()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/1b591bff-c629-15b0-de7a-c428c23e8acd.png)

`geom_path()`と`geom_line()`の違いは、点列を結ぶ順序の違いです。

- `geom_path()` : データの順に結ぶ
- `geom_line()` : x軸に沿った順に結ぶ

なお、端は矢印にもできます。

```R:R
ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_text(aes(label = id2), nudge_x = 0.1, show.legend = FALSE) +
  geom_path(arrow = arrow(), show.legend = FALSE)

ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_text(aes(label = id2), nudge_x = 0.1, show.legend = FALSE) +
  geom_line(arrow = arrow(), show.legend = FALSE)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5c8213c6-c040-14ba-7ec9-cd994556b1a9.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f3eb32e3-f4f6-2f8f-9d10-b81e516a1828.png)

なので、次はどちらも同じ結果になります。

```R:R
ggplot(data = iris_id, aes(x = id2, y = Sepal.Length, color = Species)) +
  geom_path()

ggplot(data = iris_id, aes(x = id2, y = Sepal.Length, color = Species)) +
  geom_line()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f688a16f-907d-76ef-9b7b-c426001cfced.png)


#### geom_polygon()

x座標, y座標に指定した点列$(x_i, y_i)$を順に結んでできる多角形を描きます。

```R:R
ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_polygon(aes(fill = Species), alpha = 0.2)

ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(show.legend = FALSE) +
  geom_text(aes(label = id2), nudge_x = 0.1, show.legend = FALSE) +
  geom_polygon(aes(fill = Species), alpha = 0.2)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/2fc896ca-c2d6-3c93-aedf-80f764996ab6.png)


#### geom_rect()

点(xmin, ymin)と点(xmax, ymax)を結ぶ線分を対角線とする長方形を描きます。

```R:R
ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_rect(aes(xmin = Sepal.Length - 0.2, xmax = Sepal.Length + 0.2,
                ymin = Sepal.Width - 0.05, ymax = Sepal.Width + 0.05,
                fill = Species), alpha = 0.2)

ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_text(aes(label = id2), nudge_x = 0.1, show.legend = FALSE) +
  geom_rect(aes(xmin = Sepal.Length - 0.2, xmax = Sepal.Length + 0.2,
                ymin = Sepal.Width - 0.05, ymax = Sepal.Width + 0.05,
                fill = Species), alpha = 0.2)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/ca4ddb0e-28db-c0ad-1a05-963e61d24e7f.png)


#### geom_ribbon()

`geom_line()`が（x軸方向に沿った）折れ線を描くのに対して、`geom_ribbon()`は（x軸方向に沿って、y軸方向にymin～ymaxの幅を持った）リボンを描きます。

- `geom_line()`　：x軸方向に沿った折れ線を描く
- `geom_ribbon()`：x軸方向に沿ったリボンを描く

```R:R
ggplot(data = iris_id, aes(x = id2, y = Sepal.Length, color = Species)) +
  geom_line() +
  geom_ribbon(aes(ymin = Sepal.Length - 0.2, ymax = Sepal.Length + 0.2,
                  fill = Species), alpha = 0.3)

ggplot(data = iris_id, aes(x = id2, y = Sepal.Length)) +
  geom_line(aes(color = Species)) +
  geom_ribbon(aes(ymin = Sepal.Length - 0.2, ymax = Sepal.Length + 0.2,
                  fill = Species), alpha = 0.3)

ggplot(data = iris_id, aes(x = id2, y = Sepal.Length)) +
  geom_line(aes(color = Species)) +
  geom_ribbon(aes(ymin = Sepal.Length - 0.2, ymax = Sepal.Length + 0.2,
                  group = Species),
              fill = "orange", alpha = 0.3)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/1fd02f2a-e009-58a3-f996-8fe427ad18da.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/42e224b2-9c1c-dbb9-3adb-8f69b25b429b.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/33f9e36e-52a9-7947-6822-0081ca645c83.png)


`orientation = "y"`とするとx軸方向にxmin～xmaxの幅を持ったリボンを描きます。

- `geom_line(orientation = "y")`　：y軸方向に沿った折れ線を描く
- `geom_ribbon(orientation = "y")`：y軸方向に沿ったリボンを描く

```R:R
ggplot(data = iris_id, aes(x = Sepal.Length, y = id2, color = Species)) +
  geom_line(orientation = "y") +
  geom_ribbon(aes(xmin = Sepal.Length - 0.2, xmax = Sepal.Length + 0.2,
                  fill = Species), alpha = 0.3, orientation = "y")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e2adbf53-a711-c98c-6a22-57de6905adac.png)


### LINE SEGMENTS

#### geom_abline()

指定した切片と傾きの直線を描きます。

```R:R
ggplot(data = iris_id, aes(x = id2, y = Sepal.Length)) +
  geom_line(aes(color = Species)) +
  geom_abline(aes(intercept = 5, slope = 2/50), color = "darkgray")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3fd47427-2c3a-4cf5-e8b1-d3b15fe66726.png)


#### geom_hline(), geom_vline()

`geom_hline()`は水平方向（horizontal direction）、`geom_vline()`は鉛直方向（vertical direction）の直線を描きます。

- `geom_hline()`：水平方向（horizontal direction）の直線（水平線）を描く
- `geom_vline()`：鉛直方向（vertical direction）の直線を描く

```R:R
iris_mean <- iris_id %>%
  group_by(Species) %>%
  mutate(mean = mean(Sepal.Length)) %>% ungroup() %>% print()
# # A tibble: 150 x 8
#       id   id2 Sepal.Length Sepal.Width Petal.Length Petal.Width Species  mean
#    <int> <int>        <dbl>       <dbl>        <dbl>       <dbl> <fct>   <dbl>
#  1     1     1          5.1         3.5          1.4         0.2 setosa   5.01
#  2     2     2          4.9         3            1.4         0.2 setosa   5.01
#  3     3     3          4.7         3.2          1.3         0.2 setosa   5.01
#  4     4     4          4.6         3.1          1.5         0.2 setosa   5.01
#  5     5     5          5           3.6          1.4         0.2 setosa   5.01
#  6     6     6          5.4         3.9          1.7         0.4 setosa   5.01
#  7     7     7          4.6         3.4          1.4         0.3 setosa   5.01
#  8     8     8          5           3.4          1.5         0.2 setosa   5.01
#  9     9     9          4.4         2.9          1.4         0.2 setosa   5.01
# 10    10    10          4.9         3.1          1.5         0.1 setosa   5.01
# # ... with 140 more rows

ggplot(data = iris_mean, aes(x = id2, y = Sepal.Length)) +
  geom_line(aes(color = Species)) +
  geom_hline(aes(yintercept = mean, color = Species)) +
  geom_hline(yintercept = mean(iris$Sepal.Length), color = "darkgray")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a47dfb2c-f734-8365-902c-1d3cd4cb1b8c.png)

```R:R
ggplot(data = iris_id, aes(x = id2, y = Sepal.Length)) +
  geom_line(aes(color = Species)) +
  geom_vline(xintercept = seq(0, 50, by = 10), linetype = "dotted")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5581c771-9489-a82a-3c21-b411bae4de85.png)


#### geom_segment()

点(x, y)と点(xend, yend)を結ぶ線分を描きます。

```R:R
ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_segment(aes(xend = Sepal.Length + 0.5,
                   yend = Sepal.Width + 0.1))

ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_segment(aes(xend = Sepal.Length + 0.5,
                   yend = Sepal.Width + 0.1)) +
  geom_segment(x = 6, xend = 6.5,
               y = 3, yend = 3.1,
               color = "black")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/2c52b0d8-803d-4a65-1afd-4930e0bd7da2.png)


#### geom_spoke()

`geom_segment()`が始点と終点を指定して線分を描くのに対して、`geom_spoke()`は始点と仰角・半径を指定して線分を描きます。

- `geom_segment()`：始点と終点を指定して線分を描く
- `geom_spoke()`　：始点と仰角・半径を指定して線分を描く

```R:R
ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_spoke(angle = pi/6, radius = 0.2) +
  geom_spoke(aes(x = 6, y = 3),
             angle = pi/6, radius = 0.2,
             color = "black") 
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/1cc87903-babf-a525-3971-50f3fc275bda.png)

`line`, `path`, `segment`, `spoke`, `curve` の端は矢印にもできます。

```R:R
ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_text(aes(label = id2), nudge_x = 0.1, show.legend = FALSE) +
  geom_spoke(aes(angle = pi/3 * id2), radius = 0.2,
             arrow = arrow(length = unit(0.05, "npc")), show.legend = FALSE) +
  geom_spoke(aes(x = 6, y = 3),
             angle = pi/2, radius = 0.5,
             arrow = arrow(length = unit(0.05, "npc")),
             color = "darkgray")

ggplot(data = iris_head3, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_text(aes(label = id2), nudge_x = 0.1, show.legend = FALSE) +
  geom_spoke(aes(angle = pi/3 * id2), radius = 0.2,
             arrow = arrow(length = unit(0.05, "npc")), show.legend = FALSE) +
  geom_spoke(aes(x = 6, y = 3),
             angle = pi/2, radius = 0.5,
             arrow = arrow(length = unit(0.05, "npc")),
             color = "darkgray") +
  xlim(4.5, 7.5) + ylim(2.5, 4) +
  coord_fixed(ratio = 1) # 縦軸と横軸の比を1に固定
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/cbd83140-676e-f82e-56a1-5cbb28d742e6.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/ff8e34b3-aaa1-2a0c-b43a-3dd1a488ed4d.png)


## ONE VARIABLE

### continuous

#### geom_area(stat = "bin") 

`geom_line()`が（x軸方向に沿った）折れ線を描くのに対して、`geom_area()`は折れ線より下の面を塗りつぶします（y軸方向に0～yの幅を持ったリボンを描くともいえます。）。

- `geom_line()`：（x軸方向に沿った）折れ線（折れ線グラフ）を描く
- `geom_area()`：（x軸方向に沿った）面グラフ（積み上げ折れ線グラフ）を描く

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_area(stat = "bin")

ggplot(data = iris, aes(Sepal.Length)) +
  geom_area(stat = "bin", aes(color = Species, fill = Species), position = "stack")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5651e7f1-20ea-8d69-8045-49a1cb4fa942.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/b9f34833-5d9e-fbd6-a5af-165706b37cf6.png)


#### geom_density()

密度曲線（密度推定された曲線）を描きます。

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_density()

ggplot(data = iris, aes(Sepal.Length)) +
  geom_density(aes(color = Species, fill = Species), position = "identity", alpha = 0.3)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3801cf39-a681-1dcd-0047-b45ef2bf7b8f.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/27b715f0-ce57-39f6-1771-52fdb6543ece.png)


#### geom_dotplot()

ドットプロットを描きます。

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(binwidth = 0.1)

ggplot(data = iris, aes(Sepal.Length, color = Species, fill = Species)) +
  geom_dotplot(binwidth = 0.1, alpha = 0.3)
ggplot(data = iris, aes(Sepal.Length, color = Species, fill = Species)) +
  geom_dotplot(binwidth = 0.1, alpha = 0.3, position = "identity")

ggplot(data = iris, aes(Sepal.Length, color = Species, fill = Species)) +
  geom_dotplot(binwidth = 0.1, alpha = 0.3, position = "dodge")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/ec4921fe-3384-5255-0c07-22f3b3188a7b.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/72d68b67-9eba-78ac-bbf1-e5811b2dadf6.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/cd6db0d3-8102-a2b3-b1e6-a158cdc492c7.png)


#### geom_freqpoly()

度数曲線を描きます。

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_freqpoly(binwidth = 0.1)

ggplot(data = iris, aes(Sepal.Length, color = Species)) +
  geom_freqpoly(binwidth = 0.1)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/1fdf4bb9-bca4-1280-b225-95ff595b624a.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/b0b888d7-cba5-f24c-80fd-df7cb21869fa.png)


#### geom_histogram()

ヒストグラムを描きます。

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_histogram(binwidth = 0.1)

ggplot(data = iris, aes(Sepal.Length, color = Species, fill = Species)) +
  geom_histogram(binwidth = 0.1)
ggplot(data = iris, aes(Sepal.Length, color = Species, fill = Species)) +
  geom_histogram(binwidth = 0.1, position = "stack")

ggplot(data = iris, aes(Sepal.Length, color = Species, fill = Species)) +
  geom_histogram(binwidth = 0.1, position = "identity", alpha = 0.3)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/b006a985-952e-6ba9-d237-8ad08cdc8041.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/65ad6158-c875-f663-3db5-f8f61b1fe312.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f9e1a188-38a9-f37b-4a4a-4aa84485e61c.png)

重ね合わせてみます。

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_histogram(aes(fill = Species), binwidth = 0.1, position = "identity", alpha = 0.3) +
  geom_freqpoly(aes(color = Species), binwidth = 0.1, position = "identity")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/63a83060-dce6-d3ee-02c3-b2ef4a1277c3.png)


`..count..`, `..density..`, `..ncount..`, `..ndensity..`

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = ..count..)) +
  geom_histogram(aes(color = Species, fill = Species), alpha = 0.2, position = "identity", binwidth = 0.2) +
  scale_x_continuous(breaks = seq(4, 8, by=0.4))
ggplot(data = iris, aes(x = Sepal.Length, y = stat(count))) +
  geom_histogram(aes(color = Species, fill = Species), alpha = 0.2, position = "identity", binwidth = 0.2) +
  scale_x_continuous(breaks = seq(4, 8, by=0.4))

ggplot(data = iris, aes(x = Sepal.Length, y = ..density..)) +
  geom_histogram(aes(color = Species, fill = Species), alpha = 0.2, position = "identity", binwidth = 0.2) +
  scale_x_continuous(breaks = seq(4, 8, by=0.4))

ggplot(data = iris, aes(x = Sepal.Length, y = ..ncount..)) +
  geom_histogram(aes(color = Species, fill = Species), alpha = 0.2, position = "identity", binwidth = 0.2) +
  scale_x_continuous(breaks = seq(4, 8, by=0.4))

ggplot(data = iris, aes(x = Sepal.Length, y = ..ndensity..)) +
  geom_histogram(aes(color = Species, fill = Species), alpha = 0.2, position = "identity", binwidth = 0.2) +
  scale_x_continuous(breaks = seq(4, 8, by=0.4))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/66b5c550-cf5f-91f2-4b90-d8ba6ec91ab1.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d50a7b2b-275f-83d2-27af-6d57c71b2d7d.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/1d27c41d-2f43-a0b2-caed-05d72547b8a8.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/886091d4-d747-472d-9af2-022c6874cbb0.png)


`ggplot_build()`を用いると内部的に計算されているヒストグラムの情報を取得することができます。
参考：https://heavywatal.github.io/rstats/ggplot2.html#内部変数を使う

```R:R
p0 <- ggplot(data = iris, aes(x = Sepal.Length, y = ..count..)) +
  geom_histogram(binwidth = 0.5, boundary = 4.0, color = "black") +
  scale_x_continuous(breaks = seq(4.0, 8.0, by=0.5))
plot(p0)

p1 <- ggplot(data = iris, aes(x = Sepal.Length, y = ..count..)) +
  geom_histogram(binwidth = 0.5, boundary = 4.1, color = "black") +
  scale_x_continuous(breaks = seq(4.1, 8.1, by=0.5))
plot(p1)

p2 <- ggplot(data = iris, aes(x = Sepal.Length, y = ..count..)) +
  geom_histogram(binwidth = 0.5, boundary = 4.2, color = "black") +
  scale_x_continuous(breaks = seq(4.2, 8.2, by=0.5))
plot(p2)

p3 <- ggplot(data = iris, aes(x = Sepal.Length, y = ..count..)) +
  geom_histogram(binwidth = 0.5, boundary = 4.3, color = "black") +
  scale_x_continuous(breaks = seq(4.3, 8.3, by=0.5))
plot(p3)

ggplot_build(p0)$data[[1]]$count
# [1]  5 27 27 30 31 18  6  6
ggplot_build(p1)$data[[1]]$count
# [1]  9 32 24 30 27 17  6  5
ggplot_build(p2)$data[[1]]$count
# [1] 11 34 28 26 31 12  7  1
ggplot_build(p3)$data[[1]]$count
# [1] 16 30 34 28 25 10  6  1

table(cut(iris$Sepal.Length, breaks = seq(4.0, 8.0, by = 0.5), include.lowest = TRUE))
# 
# [4,4.5] (4.5,5] (5,5.5] (5.5,6] (6,6.5] (6.5,7] (7,7.5] (7.5,8] 
#       5      27      27      30      31      18       6       6 
table(cut(iris$Sepal.Length, breaks = seq(4.1, 8.1, by = 0.5), include.lowest = TRUE))
# 
# [4.1,4.6] (4.6,5.1] (5.1,5.6] (5.6,6.1] (6.1,6.6] (6.6,7.1] (7.1,7.6] (7.6,8.1]
#         9        32        24        30        27        17         6         5 
table(cut(iris$Sepal.Length, breaks = seq(4.2, 8.2, by = 0.5), include.lowest = TRUE))
# 
# [4.2,4.7] (4.7,5.2] (5.2,5.7] (5.7,6.2] (6.2,6.7] (6.7,7.2] (7.2,7.7] (7.7,8.2] 
#        11        34        28        26        31        12         7         1 
table(cut(iris$Sepal.Length, breaks = seq(4.3, 8.3, by = 0.5), include.lowest = TRUE))
# 
# [4.3,4.8] (4.8,5.3] (5.3,5.8] (5.8,6.3] (6.3,6.8] (6.8,7.3] (7.3,7.8] (7.8,8.3] 
#        16        30        34        28        25        10         6         1 
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/962deedd-cf2b-d834-82d2-72832c65981c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/803cbcb8-de86-1f1b-34e7-dea66e0e4df2.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f2182f1c-1442-44a4-b540-18f53aeeffe3.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/7de5423e-de9b-6374-2b14-157cae1451f7.png)


#### geom_qq()

QQ-プロットを描きます。

```R:R
ggplot(data = iris, aes(sample = Sepal.Length)) +
  geom_qq() +
  stat_qq_line()

ggplot(data = iris, aes(sample = Sepal.Length, color = Species)) +
  geom_qq() +
  stat_qq_line()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/065a754f-d52a-98ed-af33-aa4faef2cecd.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/13006c70-086c-85b6-3b68-260214c645c8.png)


### descrete

#### geom_bar()

x軸に指定した離散値ごとに`stat_count()`でカウントした値をy軸にした棒グラフを描きます。

- `geom_bar()`：カウント数をy軸にとった棒グラフを描く
- `geom_col()`：指定した値をy軸にとった棒グラフを描く

```R:R
ggplot(data = iris, aes(x = Species)) +
  geom_bar()
ggplot(data = iris, aes(x = Species, y = ..count..)) +
  geom_bar()
ggplot(data = iris, aes(x = Species, y = stat(count))) +
  geom_bar()
ggplot(data = iris, aes(x = Species, y = after_stat(count))) +
  geom_bar()

ggplot(data = iris_round, aes(x = round_sl)) +
  geom_bar()
ggplot(data = iris_round, aes(x = round_sl, y = stat(count))) +
  geom_bar()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/20830733-5c8b-9b59-7a7c-8b713ba6ee86.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3ba77027-6549-fbd3-4812-a8d85e67b6e6.png)

`position`で棒グラフの種類を設定できます。

- `position = "stack"`：積み上げ棒グラフ（エクセルの「積み上げ縦棒」）
- `position = "fill"`：全体を100％にした積み上げ棒グラフ（エクセルの「100％積み上げ縦棒」）
- `position = "identity"`：棒グラフの重ね合わせ
- `position = "dodge"`, `"dodge2"`：横並びの棒グラフ（エクセルの「集合縦棒」）

```R:R
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar()
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = "stack")
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_stack())

ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = "fill")
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_fill())

ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = "identity", alpha = 0.2)
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_identity(), alpha = 0.2)

ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = "dodge")
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_dodge())
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_dodge(preserve = "total"))

ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = "dodge2")
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_dodge2())
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_dodge2(preserve = "total"))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/6238bc3c-f366-3d93-1ec6-7e70acfaffb3.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/4ec900c6-70b6-c4bf-0625-ec878703b00c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/c0346ce8-a503-133f-4ef6-4837ae34e739.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/402c2431-cee5-f294-f7cc-fa02cb913b53.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/57da6ded-c76c-e48c-b646-c5224be228af.png)

`position_dodge()`と`position_dodge2()`の違いは、`preserve = "single"`とするとよくわかります。

- `position_dodge(preserve = "single")`：どのxでもグループごとの配置は同じ
- `position_dodge2(preserve = "single")`：xごとに全体を真ん中に配置

```R:R
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_dodge(preserve = "single"))

ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = position_dodge2(preserve = "single"))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a2595bf3-c02f-2d2d-7170-a07e45ee1fec.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/b55cb7bb-588b-2828-9228-1f809341f85c.png)

`width`で棒の幅を調整できます。

```R:R
ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = "stack", width = 0.6)

ggplot(data = iris_round, aes(x = round_sl, color = Species, fill = Species)) +
  geom_bar(position = "dodge", width = 0.6)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/ba513824-65aa-942c-fefb-9a410ade23d6.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/66d6a124-172b-c1d8-ab72-3ab0393056d8.png)

irisデータは0.1単位ですので、roundせずにそのままx軸に指定すると、ビン幅が0.1のヒストグラムと同じようになります。

```R:R
ggplot(data = iris, aes(x = Sepal.Length)) +
  geom_bar(width = 0.1)

ggplot(data = iris, aes(x = Sepal.Length, color = Species, fill = Species)) +
  geom_bar(width = 0.1)
ggplot(data = iris, aes(x = Sepal.Length, color = Species, fill = Species)) +
  geom_bar(position = "stack", width = 0.1)

ggplot(data = iris, aes(x = Sepal.Length, color = Species, fill = Species)) +
  geom_bar(position = "identity", alpha = 0.2, width = 0.1)

ggplot(data = iris, aes(x = Sepal.Length, color = Species, fill = Species)) +
  geom_bar(position = position_dodge(preserve = "single"), width = 0.1)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d03d322c-c31f-c762-04d2-a84f7f206b5f.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e37d1b11-aa1c-20f6-33f8-746281aba3b5.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/751d960b-7df8-4301-0356-955d86088977.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5d970d25-735b-b59a-f8d9-bf0f39a026d5.png)


## TWO VARIABLES

### continuous x, continuous y

#### geom_label()

`geom_text()`が指定した座標(x, y)にテキストを入れるのに対して、`geom_label()`は指定した座標(x, y)にラベルを貼ります。

- `geom_text()` ：指定した座標(x, y)にテキストを入れる
- `geom_label()`：指定した座標(x, y)にラベルを貼る

```R:R
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_label(aes(label = id2))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/244e6583-9dd8-a4ce-cc87-5f1361e8a9ae.png)

`nudge_x`, `nudge_y`でラベルの位置をずらせます。
`show.legend = FALSE`とすることで凡例に表示しないようにできます。

```R:R
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_label(aes(label = id2)) +
  geom_point()

ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_label(aes(label = id2), nudge_x = 0.1, nudge_y = 0.05) +
  geom_point()

ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_label(aes(label = id2), nudge_x = 0.1, nudge_y = 0.05, show.legend = FALSE) +
  geom_point()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a1c1f025-6f50-c776-051d-5827d0e1f091.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/78263739-d10a-3285-5eb4-8e92ad7a32aa.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/deb8d59d-06dd-f529-ac07-6bbb9934c388.png)


#### geom_jitter()

`geom_point()`が指定した座標に点をプロットするのに対して、`geom_jitter()`は指定した座標を中心にして点をランダムにばらけさせます。

- `geom_point()` ：指定した座標に点をプロット
- `geom_jitter()`：指定した座標を中心に点をばらけさせてプロット

```R:R
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_jitter(width = 0.05, height = 0.05)

ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(shape = 3) # 元の場所：＋印

set.seed(1)
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_jitter(width = 0.05, height = 0.05) +
  geom_point(shape = 3) # 元の場所：＋印
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/9e6d4aee-58a3-4474-14ee-91e7c88f8ad0.png)


#### geom_point()

指定した座標に点をプロットすることで散布図を描きます。

```R:R
ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point()

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bcce286f-96c6-f0b3-0d50-7773f02b8697.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/63caf0de-142b-7fff-d454-95d795d4f00c.png)


#### geom_quantile()

分位点回帰の曲線を描きます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_quantile()
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_quantile(quantile = c(0.25, 0.75))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/19e8aeb1-366b-a7a1-7b55-3f1ef4488d9a.png)


#### geom_rug()

ラグプロット（2次元分布の周辺分布（marginal distributions））を描きます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_rug()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/71058635-3c97-6fd2-47c0-8b870037f2f7.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_rug()
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_rug(sides = "bl") # a string containing any of "trbl", for top, right, bottom, and left.

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_rug(sides = "bl", show.legend = FALSE)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/fb6ffb59-102e-0421-3797-5b7ea45b9fc6.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/01520e6c-5d39-efde-8f3d-9918a3a7e2a8.png)

irisデータは0.1単位のため重なるデータが多く、rugが重なって見にくいので、jitterでずらしておきます。

```R:R
ggplot(data = iris_id, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_rug(alpha = 0.3)

ggplot(data = iris_id, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_rug(aes(x = jitter(Sepal.Length), y = jitter(Sepal.Width)), alpha = 0.3)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/c5aff2f0-da57-5e78-3a2f-6744c2208816.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/0e1620b4-7706-1ea8-34ae-943dd9f0c651.png)

重ならないデータでも試しておきます。

```R:R
set.seed(0)
x = rnorm(1000, mean = 0, sd = 1)
y = rnorm(1000, mean = 0, sd = 1)

ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point() +
  geom_rug()

ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point(alpha = 0.3) +
  geom_rug(alpha = 0.3)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/239b8617-9b58-2124-9677-74c3d50deb8c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e5116cce-8646-056f-2510-4ed115bd8df4.png)


#### geom_smooth()

回帰曲線を描きます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_smooth(method = lm)

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_smooth(method = lm, se = FALSE)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e237f8f4-2a21-ef57-f32e-9f2a28fdbfba.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/1e08b731-4e7a-add3-bee8-832975a507fd.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_smooth(method = "lm")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_smooth(method = "glm", method.args = list(family = Gamma(link = "inverse")))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_smooth(method = "loess")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e237f8f4-2a21-ef57-f32e-9f2a28fdbfba.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5c466a20-b1ba-e7e9-cf21-36b65eb1a5b7.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/29e42816-e8c6-1e3d-7c85-5957a4d640f8.png)


#### geom_text()

指定した座標(x, y)にテキストを入れます。

- `geom_text()` ：指定した座標(x, y)にテキストを入れる
- `geom_label()`：指定した座標(x, y)にラベルを貼る

```R:R
ggplot(data = iris_id, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_text(aes(label = id), size = 3)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/671163e6-9008-4e4e-0d09-29b3c277928f.png)

`nudge_x`, `nudge_y`でテキストの位置をずらせます。

```R:R
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() + 
  geom_text(aes(label = id2))

ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() + 
  geom_text(aes(label = id2), nudge_x = 0.1, nudge_y = 0.05, show.legend = FALSE)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/40e44f4f-186f-cae2-81b2-4df528882ccb.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bfc44d11-1402-7b6e-b21e-ce7c734bf2cb.png)


### discrete x, continuous y

#### geom_col()

`geom_bar()`がx軸の離散値ごとにカウントした値をy軸にした棒グラフを描くのに対して、`geom_col()`は指定した値をy軸にした棒グラフを描きます。

- `geom_bar()`：カウント数をy軸にとった棒グラフを描く
- `geom_col()`：指定した値をy軸にとった棒グラフを描く

```R:R
ggplot(data = iris_summary, aes(x = Species, y = mean)) +
  geom_col()
iris %>%
  group_by(Species) %>%
  summarise(mean = mean(Sepal.Length), sd = sd(Sepal.Length)) %>%
  ggplot(aes(x = Species, y = mean)) +
  geom_col()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/4bd994ce-5c8d-b792-c95e-0e1e5718c332.png)

なので、次はどちらも同じ結果になります。

```R:R
iris_round %>% 
  group_by(round_sl) %>% count(name = "count") %>% 
  ggplot(aes(x = round_sl, y = count)) +
  geom_col()

ggplot(data = iris_round, aes(x = round_sl)) +
  geom_bar()
ggplot(data = iris_round, aes(x = round_sl, y = ..count..)) +
  geom_bar()
ggplot(data = iris_round, aes(x = round_sl, y = stat(count))) +
  geom_bar()
ggplot(data = iris_round, aes(x = round_sl, y = after_stat(count))) +
  geom_bar()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/8e9f1fc4-e9f1-233a-f1de-9108a2400881.png)

```R:R
iris_round %>% 
  group_by(round_sl, Species) %>% count(name = "count") %>% 
  ggplot(aes(x = round_sl, y = count, fill = Species)) +
  geom_col()

ggplot(data = iris_round, aes(x = round_sl, fill = Species)) +
  geom_bar()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/705d1abc-51a5-b498-a10c-645660a42724.png)


#### geom_boxplot()

ボックスプロット（箱ひげ図）を描きます。

```R:R
ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/dbed7821-bd0b-604a-5970-a568f51ab8fe.png)


#### geom_dotplot(binaxis = "y")

ドットプロットを描きます。

```R:R
ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_dotplot(binaxis = "y")

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_dotplot(binaxis = "y", stackdir = "center")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/dfbc1ef6-f078-9bb8-6be8-e6909961d486.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/c3fd0238-f5ae-12fc-1736-c80d4cfeda0a.png)


#### geom_violin()

バイオリンプロットを描きます。
`scale`で描かれる各バイオリンの幅のスケーリングを指定できます。

- `scale = "area"` ：各バイオリンの面積を同じに（デフォルト）
- `scale = "count"`：各バイオリンの面積を観測数に比例した面積に
- `scale = "width"`：各バイオリンの最大幅を同じに

```R:R
ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_violin()
ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_violin(scale = "area")

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_violin(scale = "count")

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_violin(scale = "width")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3d27a506-3623-7403-b63f-45acb494c5f9.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/53b8d1a0-e96d-96e4-d805-b9bbed8abf2e.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/360637cd-7cbf-ca49-b1d2-94b354b0e4ae.png)

これらを重ね描きしてみます。
参考：https://yukiyanai.github.io/jp/classes/stat2/contents/R/intro-to-ggplot2.html

```R:R
ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_violin() +
  geom_boxplot(width = 0.3, fill = "gray")

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_violin() +
  geom_boxplot(width = 0.3, fill = "gray") +
  geom_dotplot(binaxis = "y", stackdir = "center", binwidth = 0.1,
               color = "orange", fill = "orange")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/2c7be756-0fa6-4419-93a0-2ac2de08e37c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/cbb5ca49-f42e-c094-eae1-a6c1a152098d.png)


##### ggbeeswarm::geom_beeswarm()

`ggbeeswarm`ライブラリの`geom_beeswarm()`でビースウォームプロット（蜂群図）(bee swarm plot)を描けます。 
参考：https://yukiyanai.github.io/jp/classes/stat2/contents/R/intro-to-ggplot2.html

```R:R
library(ggbeeswarm)

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_quasirandom()

ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_violin() +
  geom_boxplot(width = 0.3, fill = "gray") +
  geom_quasirandom(color = "orange")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/8fd9fa55-a6c2-68cd-da08-bb42613ee47d.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/0b85a229-cad8-6471-19c7-ed55d75cac1a.png)


### discrete x, discrete y

#### geom_count()

x軸、y軸の離散値ごとにカウントした値を点のサイズで表したグラフを描きます。

```R:R
ggplot(data = iris_round, aes(x = round_sl, y = round_sw)) +
  geom_count()

ggplot(data = iris_round, aes(x = round_sl, y = round_sw, color = Species)) +
  geom_count(alpha = 0.5)

ggplot(data = iris_round, aes(x = round_sl, y = round_sw, color = Species)) +
  geom_count(position = position_jitter(width = 0.1, height = 0.1, seed = 1), alpha=0.5)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f7127367-5065-e52e-ca39-c14f44850a9e.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/44ebdf73-fb1d-1169-5b92-f8f313971afb.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/10c23cc7-65ca-bcf1-48c2-f47f7b2c49d6.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_count(alpha = 0.5)

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_count(alpha = 0.5)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/6b540c44-7458-54ee-0285-955c4f706067.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/6a8080a7-4fa4-c726-e844-0a9ba7603272.png)


ボックスプロット（箱ひげ図）、バイオリンプロットと重ね描きしてみます。

```R:R
ggplot(data = iris, aes(x = Species, y = Sepal.Length)) +
  geom_violin() +
  geom_boxplot(width = 0.3, fill = "gray") +
  geom_count(color = "orange", fill = "orange", alpha = 0.5)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/0a7d852d-ce73-65a7-31a2-4fa3c36d7641.png)


### continuous bivariate distribution

#### geom_bin2d()

`geom_histogram()`がx軸に指定した連続値を`stat_bin()`で区切ったヒストグラム（1次元のヒストグラム）を描くのに対して、`geom_bin2d()`はx軸・y軸にそれぞれ指定した連続値を`stat_bin2d()`で区切った2次元のヒストグラムを描きます（ヒストグラムの高さを色で表現）。ビン幅`binwidth `も2次元のベクトルで指定します。

- `geom_histogram()`：1次元のヒストグラム
- `geom_bin2d()`　　：2次元のヒストグラム

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_bin2d(binwidth = c(0.5, 0.5))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_bin2d(binwidth = c(0.5, 0.5)) +
  geom_point(color = "orange")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_bin2d(binwidth = c(0.5, 0.5)) +
  geom_count(color = "orange")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/240bf42f-dcb8-a887-760a-742c3b33237b.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bbc7025c-7cc9-d570-0bc4-bdd9f46f99bb.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/ff290944-2da9-d6db-ae64-3165c9f1a86d.png)


#### geom_density2d()

2次元の密度関数を等高線で描きます。

- `geom_density()`　：1次元の密度関数
- `geom_density2d()`：2次元の密度関数

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_density2d()

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_density2d() +
  geom_point(color = "orange")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_density2d() +
  geom_count(color = "orange")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/53633800-1885-fa23-6bb4-ef115924b54c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/82fb6c19-f478-93eb-b15e-de433754d929.png)

Speciesごとにも描けます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_density2d()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a78739e3-d5e6-17ef-3454-46ab4314a149.png)


#### geom_hex()

`geom_bin2d()`の六角形バージョンです。

- `geom_bin2d()`：2次元ヒストグラム
- `geom_hex()`　：2次元ヒストグラムの六角形版

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_hex(binwidth = c(0.5, 0.5))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_hex(binwidth = c(0.5, 0.5)) +
  geom_point(color = "orange")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_hex(binwidth = c(0.5, 0.5)) +
  geom_count(color = "orange")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bc5c65b2-fab1-f5ba-fac2-f37c836432cf.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/87603da2-85c1-7a29-2056-10dcb1c7fad4.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/24658fa1-9b08-bc7e-d34a-078cd624c89a.png)


### continuous function

#### geom_area()

`geom_line()`が（x軸方向に沿った）折れ線を描くのに対して、`geom_area()`は折れ線より下の面を塗りつぶします（y軸方向に0～yの幅を持ったリボンを描くともいえます。）。

- `geom_line()`：（x軸方向に沿った）折れ線（折れ線グラフ）を描く
- `geom_area()`：（x軸方向に沿った）面グラフ（積み上げ折れ線グラフ）を描く

```R:R
ggplot(data = iris_id, aes(x = id, y = Sepal.Length)) +
  geom_area()

ggplot(data = iris_id, aes(x = id2, y = Sepal.Length, color = Species)) +
  geom_area(aes(fill = Species), alpha = 0.3)
ggplot(data = iris_id, aes(x = id2, y = Sepal.Length, color = Species)) +
  geom_area(aes(fill = Species), alpha = 0.3, position = "stack")
ggplot(data = iris_id, aes(x = id2, y = Sepal.Length, color = Species)) +
  geom_area(aes(fill = Species), alpha = 0.2, position = "identity")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/8ddfbd97-f057-9173-02b4-f47664cfaa76.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/35baf47b-a978-baee-a682-6d3a9dfd5918.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f10e83c0-5493-ffbd-7b30-6f4eb3dde640.png)


#### geom_line()

（x軸方向に沿った）折れ線を描きます。

```R:R
ggplot(data = iris_id, aes(x = id, y = Sepal.Length)) +
  geom_line()

ggplot(data = iris_id, aes(x = id2, y = Sepal.Length, color = Species)) +
  geom_line()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/333d24db-eee3-a3ec-8707-2cd9fd1e1223.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/2cce3e80-54a3-6e37-6d38-eaee5907d9a5.png)


#### geom_step()

`geom_line()`のstep関数バージョンです。x軸に沿って階段状に結びます。

- `geom_line()`：（x軸方向に沿った）折れ線（折れ線グラフ）を描く（点を結ぶ）
- `geom_step()`：（x軸方向に沿った）ステップ関数を描く（階段状に結ぶ）

```R:R
ggplot(data = iris_id, aes(x = id, y = Sepal.Length)) +
  geom_step()

ggplot(data = iris_id, aes(x = id2, y = Sepal.Length, color = Species)) +
  geom_step()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/82258d1d-1027-78b6-61e4-f67f81a07bf2.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a0bf6807-e612-fd9e-43c0-7a759292e6e0.png)


### visualizing error

エラーバーを描きます。

#### geom_crossbar()

```R:R
ggplot(data = iris_summary, aes(x = Species, y = mean, ymin = mean-sd, ymax = mean+sd)) +
  geom_crossbar()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3337cd1c-09d1-943d-f730-7e05e8277a74.png)

#### geom_errorbar()

```R:R
ggplot(data = iris_summary, aes(x = Species, y = mean, ymin = mean-sd, ymax = mean+sd)) +
  geom_errorbar()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d1ee02b6-4932-9297-9c2a-d6f0b88d72dd.png)


#### geom_linerange()

```R:R
ggplot(data = iris_summary, aes(x = Species, y = mean, ymin = mean-sd, ymax = mean+sd)) +
  geom_linerange()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/66b8c03c-8fcd-a3fd-8285-a155f89d6fc9.png)


#### geom_pointrange()

```R:R
ggplot(data = iris_summary, aes(x = Species, y = mean, ymin = mean-sd, ymax = mean+sd)) +
  geom_pointrange()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d2bae4eb-3aeb-bde7-53c9-1c19ff323c0b.png)

棒グラフと重ね描きしておきます。

```R:R
ggplot(data = iris_summary, aes(x = Species, y = mean)) +
  geom_col(color = "black", fill = "white", width = 0.6) +
  geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), color = "black", width = 0.3)

ggplot(data = iris_summary, aes(x = Species, y = mean)) +
  geom_col(color = "black", fill = "white", width = 0.6) +
  geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), color = "black", width = 0.3) +
  geom_jitter(data = iris, aes(y = Sepal.Length), color = "orange", width = 0.3, alpha = 0.3)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/90be6896-5b6a-9c5c-5a72-49131a653f65.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/2bd6bea5-9b06-9b45-d27f-201fc6face75.png)


### maps

#### geom_map()

色分けしたマップを描きます（地図を塗り分けます）。

```R:R
map <- map_data("state")
map$region
states <- unique(map$region)
states
length(states)
# [1] 49
df_us <- data.frame(state = states,
                    z = 1:length(states))
df_us
ggplot(data = df_us, aes(fill = z)) +
  geom_map(aes(map_id = state), map = map) +
  expand_limits(x = map$long, y = map$lat)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5c5ddcf5-c453-1886-06d8-3b141769d872.png)


## THREE VARIABLES

ここでは2次元正規分布のデータを使います。

```R:R
library(mvtnorm)
mu <- c(0, 0)
sigma <- matrix(c(4, 2, 2, 3), ncol = 2)
x <- seq(-4, 4, by = 0.5)
y <- seq(-4, 4, by = 0.5)
xy <- expand.grid(x, y)
names(xy) <- c("x", "y")
z <- dmvnorm(xy, mean = mu, sigma = sigma)
df <- cbind(xy, z)
```

#### geom_contour()

等高線を描きます。

```R:R
ggplot(df, aes(x = x, y = y)) +
  geom_contour(aes(z = z))

ggplot(df, aes(x = x, y = y)) +
  geom_contour(aes(z = z), bins = 10)

ggplot(df, aes(x = x, y = y)) +
  geom_contour(aes(z = z, colour = ..level..), bins = 10)
ggplot(df, aes(x = x, y = y)) +
  geom_contour(aes(z = z, colour = stat(level)), bins = 10)
ggplot(df, aes(x = x, y = y)) +
  geom_contour(aes(z = z, colour = after_stat(level)), bins = 10)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/07e43f53-404f-9093-1f6f-e5282efb8bdf.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/b6a7681b-e640-551c-cb81-9a2160af9879.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/7347ccad-8141-e420-67bc-bdc6aea3eac7.png)


```R:R
ggplot(df, aes(x = x, y = y)) +
  geom_contour_filled(aes(z = z), bins = 10)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/6dee58fc-c10e-4e2c-5697-b8a38a3e55fc.png)


#### geom_raster()

ヒートマップ表示（格子状（グリッド）に分けて色で表示）します。
`geom_tile()`はタイルの大きさを(x,y)座標ごとに変えられますが、`geom_raster()`はタイルの大きさをそろえるため高速らしいです。
参考：https://heavywatal.github.io/rstats/ggplot2.html#プロットの種類

```R:R
ggplot(df, aes(x = x, y = y)) +
  geom_raster(aes(fill = z))
ggplot(df, aes(x = x, y = y)) +
  geom_raster(aes(fill = z), hjust = 0.5, vjust = 0.5, interpolate = FALSE)

ggplot(df, aes(x = x, y = y)) +
  geom_raster(aes(fill = z), hjust = 0.5, vjust = 0.5, interpolate = TRUE)

ggplot(df, aes(x = x, y = y)) +
  geom_raster(aes(fill = z), hjust = 0, vjust = 0, interpolate = FALSE)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/8f8185d7-b144-49a6-7eff-2559e5365960.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e63e03cb-3a3e-8132-3d57-f4c515b237a9.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/062108ce-1f7e-5803-d64a-dac1937da678.png)

`geom_contour()`と重ね描きしておきます。

```R:R
ggplot(df, aes(x = x, y = y)) +
  geom_raster(aes(fill = z), interpolate = TRUE) +
  geom_contour(aes(z = z), bins = 10, color = "white")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5ced64a3-a889-0af1-f357-bee9cee254b2.png)


#### geom_tile()

`geom_tile()`は長方形のタイルを敷き詰めたものを描きます。`geom_rect()`が長方形の頂点を指定するのに対して、`geom_tile()`は長方形の中心と幅を指定します。

- `geom_rect()`：頂点を指定して長方形を描く
- `geom_tile()`：中心と幅を指定して長方形を描く

```R:R
ggplot(df, aes(x = x, y = y)) +
    geom_tile(aes(fill = z))

ggplot(df, aes(x = x, y = y)) +
  geom_tile(aes(fill = z), color = "gray")

ggplot(df, aes(x = x, y = y)) +
  geom_rect(aes(xmin = x, xmax = x + 0.5,
                ymin = y, ymax = y + 0.5,
                fill = z), color = "gray")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bd2ca62b-5f7e-ecad-c3fe-b0e3c5cf24d0.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/eb5ae84e-4ef1-f5df-9a9a-532ac980fcc3.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/24388376-9c8e-0ff0-1811-ac6988c6e2cd.png)

なので、次はどちらも同じ結果になります。

```R:R
ggplot(df, aes(x = x, y = y)) +
  geom_rect(aes(xmin = x - 0.5/2, xmax = x + 0.5 - 0.5/2,
                ymin = y - 0.5/2, ymax = y + 0.5 - 0.5/2,
                fill = z), color = "gray")

ggplot(df, aes(x = x, y = y)) +
  geom_tile(aes(fill = z), width = 0.5, color = "gray")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/eb5ae84e-4ef1-f5df-9a9a-532ac980fcc3.png)


# Scales

`scale_*()`関数を使います。`scale_*()`関数については、[こちら](#https://qiita.com/swathci/items/00b4a847843a33345887)にまとめました。

## Scales

#### scale_fill_manual()

`fill`軸の手動による設定ができます。

```R:R
ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = factor(round_sl)))

ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = factor(round_sl))) +
  scale_fill_manual(values = c("skyblue", "royalblue", "blue", "navy"),
                    limits = str_c(4:7),
                    breaks = str_c(4:7),
                    name = "Sepal.Length",
                    labels = str_c(4:7, ".0 - ", 4:7+1, ".0"))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/dc8fa309-bee3-36af-4453-0de39ac05a20.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f4f05a86-9b2a-bffa-5b98-bc64127a9be0.png)


## GENERAL PURPOSE SCALES


## X & Y LOCATION SCALES

#### scale_x_log10()

x軸をlogスケール（対数目盛）にします。
y軸の場合は`scale_y_log10()`を使います。

```R:R
ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point()

ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  scale_x_log10() + scale_y_log10()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/da8b87c1-626a-fbdb-72ff-96cd1edead99.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a8db710a-f2f2-1e2f-20bf-31fd60af9e14.png)

logスケール（対数目盛）の効果がわかりやすいように別のデータでも描いておきます。

```R:R
x <- 1:5
y <- 10^x

ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point()

ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point() +
  scale_y_log10()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/181c91b5-1bdf-bb3b-2d7a-9501f5cadd62.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/7efa49a1-dd08-e598-0456-86777369129e.png)

```R:R
set.seed(1)
x <- rlnorm(1000, meanlog = 0, sdlog = 1)

ggplot() +
  geom_histogram(aes(x = x))

ggplot() +
  geom_histogram(aes(x = x)) +
  scale_x_log10()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d66a985d-4917-bde0-677e-e0057eb5344e.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/c2dae038-899f-9dcf-9f8f-ee8adcddf606.png)


#### scale_x_reverse()

x軸を反転します。
y軸の場合は`scale_y_reverse()`を使います。

```R:R
ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point()

ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  scale_x_reverse() + scale_y_reverse()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/da8b87c1-626a-fbdb-72ff-96cd1edead99.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/31bdd6a9-9c3a-ce35-298f-c27854902110.png)


#### scale_x_sqrt()

x軸をsqrtスケールにします。
y軸の場合は`scale_y_sqrt()`を使います。

```R:R
ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point()

ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  scale_x_sqrt() + scale_y_sqrt()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/da8b87c1-626a-fbdb-72ff-96cd1edead99.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/51698000-cba9-0985-6202-134978e8c44e.png)

sqrtスケールの効果がわかりやすいように別のデータでも描いておきます。

```R:R
x <- seq(0, 10, by = 1)
y <- x ^ 2

ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point()

ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point() +
  scale_y_sqrt()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/b199ab22-a653-8a78-6146-52d6e0a2c136.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/ace4fa6d-a6e5-a8be-db1c-4aa1416466cc.png)


## COLOR AND FILL SCALES (DISCRETE)

離散値の場合の`color`・`fill`軸の設定です。

#### scale_fill_brewer()

```R:R
ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = round_sl)) +
  scale_fill_brewer(palette = "Blues")

ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = round_sl)) +
  scale_fill_brewer(palette = "Blues", direction = -1)

ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = round_sl)) +
  scale_fill_brewer(palette = "Accent")

ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = round_sl)) +
  scale_fill_brewer(palette = "Set1")

ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = round_sl)) +
  scale_fill_brewer(palette = "Set2")

ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = round_sl)) +
  scale_fill_brewer(palette = "Set3")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/6ccb24e6-ad91-fa53-962d-d008a56b0e85.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e8d07784-81e4-62d0-e77b-26f2ff631b3e.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/24c8d57b-638f-2793-a71e-435b4a5fc229.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/147cbf71-72e8-b6f3-df2e-24143d8c3bdd.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/99743fb0-cdbe-efda-3157-db9278d90c03.png)


#### scale_fill_grey()

```R:R
ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = round_sl)) +
  scale_fill_grey(start = 0.8, end = 0.2, na.value = "red")

ggplot(data = iris_round) +
  geom_bar(aes(x = round_sl, fill = round_sl)) +
  scale_fill_grey(start = 0.1, end = 0.5, na.value = "red")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/0763bf88-36a1-0da0-f4bd-ba5b364f4eba.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/861b7986-ad49-01d0-1381-8ec7d01a8b7e.png)


## COLOR AND FILL SCALES (CONTINUOUS)

連続値の場合の`color`・`fill`軸の設定です。

#### scale_fill_distiller()

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot()

ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_distiller(palette = "Blues")
ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = stat(x))) +
  scale_fill_distiller(palette = "Blues")
ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = after_stat(x))) +
  scale_fill_distiller(palette = "Blues")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f0f90146-1b98-2bb3-f5b7-69aad759fcc0.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/aa77c180-6139-aa0d-8ed9-de7250e25556.png)


#### scale_fill_gradient()

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradient(low = "red", high = "yellow")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/85ee6b30-f01f-e71b-9f09-4efcce54de35.png)


#### scale_fill_gradient2()

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 6)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/001d09e3-3335-f03c-4c32-72c85ef4b560.png)


#### scale_fill_gradientn()

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradientn(colours = topo.colors(5))

ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradientn(colours = rainbow(5))

ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradientn(colours = heat.colors(5))

ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradientn(colours = terrain.colors(5))

ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradientn(colours = cm.colors(5))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/436cd92c-8596-43f3-385a-960431265b9f.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/0840a32a-aca7-010e-e2c4-e52a63b9d6ff.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/cdd49286-e91a-ca4f-bc4f-4b98bf3bea1f.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a3a73553-29d1-a990-24c6-caebe9d5c01c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/45623272-04fa-cb6f-cc65-c74f0a755b18.png)

```R:R
ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradientn(colours = RColorBrewer::brewer.pal(name = "Set1", n = 9))

ggplot(data = iris, aes(Sepal.Length)) +
  geom_dotplot(aes(fill = ..x..)) +
  scale_fill_gradientn(colours = RColorBrewer::brewer.pal(name = "Set2", n = 8))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/6d397675-79e4-7e95-1475-e14e022d2c48.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3e00c53f-0e04-c5c5-e1b2-bd7cd5b62c82.png)


```R:R
topo.colors(5)
# [1] "#4C00FFFF" "#004CFFFF" "#00E5FFFF" "#00FF4DFF" "#FFFF00FF"
rainbow(5)
# [1] "#FF0000FF" "#CCFF00FF" "#00FF66FF" "#0066FFFF" "#CC00FFFF"
heat.colors(5)
# [1] "#FF0000FF" "#FF5500FF" "#FFAA00FF" "#FFFF00FF" "#FFFF80FF"
terrain.colors(5)
# [1] "#00A600FF" "#E6E600FF" "#EAB64EFF" "#EEB99FFF" "#F2F2F2FF"
cm.colors(5)
# [1] "#80FFFFFF" "#BFFFFFFF" "#FFFFFFFF" "#FFBFFFFF" "#FF80FFFF"
RColorBrewer::brewer.pal(name = "Set1", n = 9)
# [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF" "#999999"
RColorBrewer::brewer.pal(name = "Set2", n = 8)
# [1] "#66C2A5" "#FC8D62" "#8DA0CB" "#E78AC3" "#A6D854" "#FFD92F" "#E5C494" "#B3B3B3"
```


## SHAPE AND SIZE SCALES

`shape`軸や`size`軸の設定です。

#### scale_shape(), scale_size()

```R:R
ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(shape = Species, size = Petal.Length)) +
  scale_shape(name = toupper("Species"),
              label = toupper(unique(iris$Species))) +
  scale_size(name = toupper("Petal.Length"))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/be4f0009-b0d3-d5d8-f809-499d911a9ed8.png)


#### scale_shape_manual()

`shape`軸を手動で設定します。

```R:R
ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, shape = Species))

ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, shape = Species)) +
  scale_shape_manual(values = 0:2)

ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, shape = Species)) +
  scale_shape_manual(values = 2:4)

ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, shape = Species)) +
  scale_shape_manual(values = c(19,21,22))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3c8f641a-3c9e-dd74-b2d3-b7e4974a78f8.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e6737359-5405-2212-1f6d-fbb414222a88.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/59eb1229-dde1-cc4b-f708-0544644ffacc.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/9c1f194d-a62d-bb6f-5dcd-4b06e8bf3f7c.png)


#### scale_radius()

`size`軸の半径を設定します。

```R:R
ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, size = Petal.Length))

ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, size = Petal.Length)) +
  scale_radius(range = c(1,9))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/6ca1294a-1984-79dd-f8cd-1dd1e2b64426.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/2032086d-a091-69b1-fcba-7beb07c4d703.png)


#### scale_size_area()

`size`軸の面積を設定します。

```R:R
ggplot(data = iris_head10, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, size = Petal.Length)) +
  scale_size_area(max_size = 5)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/8f9b1bd8-b0ff-e244-edeb-401037f41f49.png)


# Coordinate Systems

#### coord_cartesian()

直交座標$(x, y)$の座標軸の設定です。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species)) +
  coord_cartesian(xlim = c(2, 10), ylim = c(1, 5))
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species)) +
  xlim(2, 10) + ylim(1, 5)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/9002f9a2-097f-ddc0-75f0-4e76d5c792d7.png)


#### coord_fixed()

x軸（横軸）、y軸（縦軸）の比を固定します。
`coord_fixed(ratio = 1)`で縦横の比が同じになります。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species)) +
  coord_fixed(ratio = 1)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/820e5bf3-8c6c-b68c-a1a9-c51f95f2facb.png)


#### coord_flip()

x軸（横軸）とy軸（縦軸）を入れ替えます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species)) +
  coord_flip()
````
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a5a827df-6312-d2ff-c456-ba04ac0d1433.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d7955687-8975-f15f-2520-e966b5ac3d00.png)

```R:R
ggplot(data = iris_round, aes(x = round_sl)) +
  geom_bar()

ggplot(data = iris_round, aes(x = round_sl)) +
  geom_bar() +
  coord_flip()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/908d7982-8544-1dc5-115f-b1fdc9e05e80.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/af33c6fe-5560-588c-8681-64890485fb25.png)


#### coord_polar()

通常の直交座標$(x, y)$ではなく、極座標$(r, \theta)$でグラフを描きます。
もとの座標系の$x$と$y$のどちらを極座標の$\theta$にするかを指定します。

```R:R
ggplot(data = iris_round, aes(x = round_sl)) +
  geom_bar(width = 1, color = "black")

ggplot(data = iris_round, aes(x = round_sl)) +
  geom_bar(width = 1, color = "black") +
  coord_polar(theta = "x")

ggplot(data = iris_round, aes(x = round_sl)) +
  geom_bar(width = 1, color = "black") +
  coord_polar(theta = "y")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bf3b911a-2d95-75aa-f30f-068c64e09a68.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/cfe5874f-bdb2-510e-37f9-32af069796d7.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/98c19003-ea8a-b53f-c861-bb3c5b7d5d89.png)


これを使うと円グラフ（パイチャート）が描けます。
参考：https://www.jaysong.net/RBook/visualization1.html

```R:R
ggplot(data = iris_round) +
  geom_bar(aes(x = factor(""), fill = round_sl))

ggplot(data = iris_round) +
  geom_bar(aes(x = factor(""), fill = round_sl)) +
  coord_polar(theta = "y")

ggplot(data = iris_round) +
  geom_bar(aes(x = factor(""), fill = round_sl)) +
  labs(fill = "round(Sepal.Length)", x = "", y = "count") +
  coord_polar(theta = "y")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/21129004-3752-4e75-2c19-f1f0c7afe11c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/42c7dad7-4b1b-98f3-9482-1d0557328696.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f6289072-a6ea-4507-a223-8e28688ae974.png)

詳しくは[こちら](https://qiita.com/swathci/items/13cbe1ac34aba2bfc0ef)参照。


#### coord_trans()

座標軸のスケール変換ができます。

```R:R
ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  scale_x_sqrt() + scale_y_sqrt()
ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  coord_trans(x = "sqrt", y = "sqrt")

ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  scale_x_log10() + scale_y_log10()
ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  coord_trans(x = "log10", y = "log10")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/38f4eb5e-508e-771b-d458-dd599314e996.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/7e088dab-47f5-987e-395b-cc2b0fa8fcfb.png)



#### coord_quickmap(), coord_map()

```R:R

```


# Position Adjustments

`geom_bar()`の中で

- `position = "stack"`：積み上げ棒グラフ（エクセルの「積み上げ縦棒」）
- `position = "fill"`：全体を100％にした積み上げ棒グラフ（エクセルの「100％積み上げ縦棒」）
- `position = "identity"`：棒グラフの重ね合わせ
- `position = "dodge"`：横並びの棒グラフ（エクセルの「集合縦棒」）

```R:R
ggplot(data = iris_round, aes(x = round_sl, fill = Species)) +
  geom_bar(position = "stack")
ggplot(data = iris_round, aes(x = round_sl, fill = Species)) +
  geom_bar(position = "fill")
ggplot(data = iris_round, aes(x = round_sl, fill = Species)) +
  geom_bar(position = "identity", alpha = 0.3)
ggplot(data = iris_round, aes(x = round_sl, fill = Species)) +
  geom_bar(position = "dodge")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/03a341fe-59b8-f986-4c14-fb7fdd49570b.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5ed4b4ef-729e-59e7-bc29-e4189320c1a2.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/51337863-7322-2f71-2006-ffcb8897ce0f.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/952c527e-af2a-29ee-dca8-a41c9ce90a5a.png)

`geom_point()`の中で

- `position = "identity"`：座標の位置に配置
- `position = "jitter"`：座標の位置を中心にランダムにばらけさせた位置に配置
- `position = position_jitter()`：座標の位置を中心にランダムにばらけさせた位置に配置
- `position = position_nudge()`：座標の位置から指定した距離ずらした位置に配置

```R:R
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(shape = 3) +  # +印
  geom_point(shape = 4)    # x印

ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(shape = 3) +
  geom_point(shape = 4, position = "identity", show.legend = FALSE)

set.seed(1)
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(shape = 3) +
  geom_point(shape = 4, position = "jitter", show.legend = FALSE)

ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(shape = 3) +
  geom_point(shape = 4, position = position_jitter(width = 0.1, height = 0.05, seed = 1), show.legend = FALSE)

ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(shape = 3) +
  geom_point(shape = 4, position = position_nudge(x = 0.1, y =0.05), show.legend = FALSE)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/37cf00fa-a039-731d-3845-d9fe470e3f5a.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/8fa1fa67-aaf2-6712-1302-d44855cf83a7.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/9c2b452f-76a2-310a-30d1-02686ae53f39.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a2ff4cad-0f05-16e9-4680-b96bd1e3d3fe.png)

`geom_text()`, `geom_label()`の中で

- `position = "identity"`：座標の位置に配置
- `position = "jitter"`：座標の位置を中心にランダムにばらけさせた位置に配置
- `position = position_jitter()`：座標の位置を中心にランダムにばらけさせた位置に配置
- `position = position_nudge()`：座標の位置から指定した距離ずらした位置に配置

```R:R
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_text(aes(label = id2), size = 3,
            position = position_nudge(x = 0.1, y = 0.05), show.legend = FALSE)
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_text(aes(label = id2), size = 3,
            nudge_x = 0.1, nudge_y = 0.05, show.legend = FALSE)

ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  geom_text(aes(label = id2), size = 3,
            position = position_nudge(x = 0.1, y = 0.05), show.legend = FALSE)
```

![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/0c07c9a9-a92b-f9d2-2b2e-534099da7e59.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f6b284c2-9a1f-9593-8616-05a2c201dc40.png)

```R:R
ggplot(data = iris_head5, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species)) +
  geom_text(aes(label = id2), size = 3,
            position = position_nudge(x = 0.1, y = 0.05), show.legend = FALSE)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/f53738f6-413f-cace-8a48-0a4aea1bd85a.png)


```R:R
ggplot(data = iris_id, aes(x = Species, y = Sepal.Length, color = Species)) +
  geom_violin() +
  geom_point()

ggplot(data = iris_id, aes(x = Species, y = Sepal.Length, color = Species)) +
  geom_violin() +
  geom_point(position = position_jitter(width = 0.1), alpha = 0.4)

ggplot(data = iris_id, aes(x = Species, y = Sepal.Length, color = Species)) +
  geom_violin() +
  geom_text(aes(label = id2), size = 3, position = position_jitter(width = 0.2), show.legend = FALSE) +
  geom_rug(sides = "r", position = "jitter", alpha = 0.5)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/ae26e8a4-d426-e601-d8e5-f9a8f34cb8fb.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/e1324cd3-f435-f039-8d7f-e7f31bd3088d.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/0a5250bc-3ecb-b436-1f49-32af722e8817.png)

[こちら](https://qiita.com/swathci/items/68d0b0b83cbb4dcad7b8)も参照。


# Themes

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_bw()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/dbe1d587-cc24-3f0c-94f4-5a516a015120.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_gray()
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_grey()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/63caf0de-142b-7fff-d454-95d795d4f00c.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_dark()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/02feed74-d5cb-d33a-791a-88da80374205.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_classic()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3e9b2780-9c39-53ad-7538-01043fc89672.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_light()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d7fe9779-afc9-a2a7-9106-3358053cedb1.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_linedraw()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/9e6ac3f3-8807-0c45-38cd-4e195ce64d2c.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_minimal()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/ba01b9f9-16f2-ebdb-44d4-9cc2e6e4d333.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme_void()
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/7053810e-c7cf-1bbb-d083-009bc82ab4d3.png)


# Faceting

#### facet_grid()

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  facet_grid(cols = vars(Species))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/dff6215b-5224-805c-ce8c-a29c3a5ac8ff.png)

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  facet_grid(rows = vars(Species))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  facet_grid(rows = vars(Species)) +
  theme(strip.text.y = element_text(angle = 0))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/639e08f9-4900-21e0-e0c3-7f3e5b406f23.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/1baf1c22-4b32-9c69-b2c8-40042f00cb3d.png)

```R:R
ggplot(data = iris_round, aes(x = sl, y = sw)) +
  geom_point() +
  facet_grid(cols = vars(round_pl), rows = vars(round_pw))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d8a034ef-802a-f221-a54e-d4188a1262d2.png)

```R:R
ggplot(data = iris_round, aes(x = pl, y = pw, color = Species)) +
  geom_point() +
  facet_grid(cols = vars(round_sl), rows = vars(round_sw))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/158dc63d-08bf-6231-88d9-5c539f01de17.png)


#### facet_wrap()

```R:R
ggplot(data = iris_round, aes(x = sl, y = sw)) +
  geom_point() +
  facet_wrap(vars(round_pl))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/72f76855-28a0-7bf2-ef33-c596eeaf30c2.png)

```R:R
ggplot(data = iris_round, aes(x = pl, y = pw, color = Species)) +
  geom_point() +
  facet_wrap(vars(round_sl))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/6701294b-8545-9279-83d2-7bb5b4fdcfaf.png)


##### `scales = "free"`

```R:R
ggplot(data = iris_round, aes(x = sl, y = sw)) +
  geom_point() +
  facet_grid(cols = vars(round_pl), rows = vars(round_pw),
             scales = "free")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/54c53fe8-8834-f202-f4e2-9abb97f51393.png)


##### `scales = "free", space = "free"`

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  facet_grid(cols = vars(Species))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  facet_grid(cols = vars(Species), scales = "free")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  facet_grid(cols = vars(Species), scales = "free", space = "free")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/dff6215b-5224-805c-ce8c-a29c3a5ac8ff.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/28b415f0-f631-2d3a-2797-b349f969b03c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/294f8cf4-e1d9-76ad-4f34-ebe44a087654.png)


##### `labeller = label_both`

```R:R
ggplot(data = iris_round, aes(x = sl, y = sw)) +
  geom_point() +
  facet_grid(cols = vars(round_sl), rows = vars(round_sw),
             labeller = label_both)
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/85606d8b-a483-a52e-5564-4cf74dc2945b.png)


##### `label_bquote()`

```R:R
ggplot(data = iris_round, aes(x = pl, y = pw, color = Species)) +
  geom_point() +
  facet_grid(rows = vars(Species),
             scales = "free",
             labeller = label_bquote(Species: .(Species)))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/b1e6ee1c-b017-5a93-849f-28a211f21763.png)


# Labels

#### labs()

`labs()`でタイトル等のラベルを設定できます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  labs(title = "Scatterplot of the sepal length and sepal width",
       subtitle = "Colored by Species",
       caption = "Source: Iris data",
       x = "sepal length", y = "sepal width",
       color = "species")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  labs(title = "Scatterplot of the sepal length and sepal width",
       subtitle = "Colored by Species",
       caption = "Source: Iris data",
       tag = "A",
       x = "sepal length", y = "sepal width",
       color = "species")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/7af745aa-8ee6-a918-d4ce-2b4ec9e734bd.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/5dddcf06-25e7-3adc-7531-ac28c3e5f137.png)


#### annotate()

`annotate()`でグラフに図形や文字列を加えられます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  annotate(geom = "rect",
           xmin = 7.0, xmax = 8.0, ymin = 4.25, ymax = 4.5,
           color = "darkgray", fill = "lightgray") +
  annotate(geom = "text", x = 7.5, y = 4.4, label = "iris")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/a64eb05f-e04c-5e31-8c26-0e034e9f609d.png)


# Legends

#### theme()

##### legend.position

凡例の位置を指定します。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point()
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "right")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "left")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "top")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "bottom")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "none")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bcce286f-96c6-f0b3-0d50-7773f02b8697.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/920d089f-4a13-ad3a-26ef-d5bdc79f1612.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/2dca79f4-39fa-2e3d-703a-821559a498f3.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/c4828680-5ece-c640-7bb4-5efe1716756f.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d7e21c2c-3bd4-8beb-1f53-4f4c9f8813db.png)

凡例を図の内側に表示することもできます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = c(0.5, 0.5))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = c(0.98, 0.97), legend.justification = c("right", "top"))
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = c(0.98, 0.97), legend.justification = c(1, 1))

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = c(0.02, 0.97), legend.justification = c("left", "top"))
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = c(0.02, 0.97), legend.justification = c(0, 1))

ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = c(1, 0), 
        legend.justification = c(1, 0),
        legend.background = element_blank(),
        legend.key = element_blank())

ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = c(0.02, 0.97),
        legend.justification = c(0, 1),
        legend.background = element_rect(color = "gray", fill = alpha("gray", alpha = 1/4)),
        legend.key = element_blank())
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/9a2b4bfa-3d72-7372-e7a4-6d6754d9ff28.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3e2b3365-8704-32a1-b30a-415d739def2c.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/4de02bc0-0125-6f8f-8a38-11bc985a4265.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/841470e0-8c43-1a80-59bf-89b0a8e72b02.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bda762c1-bf2b-7ecf-96e5-0f039046d814.png)


##### legend.justification

凡例の揃え位置を指定します。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "right", legend.justification = "center")  # デフォルト

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "right", legend.justification = "top")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "right", legend.justification = "bottom")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "top", legend.justification = "left")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  theme(legend.position = "bottom", legend.justification = "right")
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/bcce286f-96c6-f0b3-0d50-7773f02b8697.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/40397953-c792-2b06-745d-039a863e15bd.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/7f639d9d-3674-6111-309a-378eb7cc3e8f.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/d1481aed-423c-ae42-588c-ad30947eaf6f.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/98f3711e-7e27-6e1b-751c-43d0d88097ff.png)


##### 複数凡例

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, size = Petal.Length)) +
  guides(size = guide_legend(nrow = 1)) +
  theme(legend.position = "bottom",      # 凡例の位置
        legend.direction = "horizontal", # 凡例値の配置方向
        legend.justification = "left",   # 凡例の揃え位置
        legend.box = "vertical",         # 複数凡例の配置方向
        legend.box.just = "left",        # 複数凡例の揃え位置
        legend.margin = margin(0, 0, 0, 0),      # 複数凡例のージン
        legend.box.margin = margin(0, 0, 0, 0))  # 凡例全体のマージン
# margin(t = 0, r = 0, b = 0, l = 0, unit = "pt")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, size = Petal.Length)) +
  guides(size = guide_legend(nrow = 2)) +
  guides(color = guide_legend(nrow = 2)) +
  theme(legend.position = "bottom",      # 凡例の位置
        legend.direction = "vertical",   # 凡例値の配置方向
        legend.justification = "center", # 凡例の揃え位置
        legend.box = "horizontal",       # 複数凡例の配置方向
        legend.box.just = "top",         # 複数凡例の揃え位置
        legend.margin = margin(0, 10, 0, 10),    # 複数凡例のージン
        legend.box.margin = margin(0, 0, 0, 0))  # 凡例全体のマージン

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(color = Species, size = Petal.Length)) +
  guides(size = guide_legend(nrow = 3)) +
  guides(color = guide_legend(nrow = 3)) +
  theme(legend.position = "right",     # 凡例の位置
        legend.direction = "vertical", # 凡例値の配置方向
        legend.justification = "top",  # 凡例の揃え位置
        legend.box = "vertical",       # 複数凡例の配置方向
        legend.box.just = "left",      # 複数凡例の揃え位置
        legend.margin = margin(5, 0, 5, 0),      # 複数凡例のージン
        legend.box.margin = margin(0, 0, 0, 0))  # 凡例全体のマージン
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/9f7cd9fa-8980-ce7f-f4ac-b2939952802b.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/55d2fcee-6343-3942-9295-a81faaa21690.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/7bad524d-6b82-7212-4287-b92bc465ba9f.png)



#### guides()

各軸の凡例について、`guides(軸名 = ***)`の形で設定します。

##### guide_none(), "none"

`guides(color = "none")`または`guides(color = FALSE)`とすると`color`の凡例を非表示にできます。`x`, `y`については、`guides(x = "none")`を`guides(x = FALSE)`とはできません。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(color = guide_none())
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(color = "none")
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(color = FALSE)

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(x = guide_none()) +
  guides(y = guide_none())
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(x = "none") +
  guides(y = "none")
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(x = guide_none(), y = guide_none())
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(x = "none", y = "none")

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(x = FALSE, y = FALSE)
# エラー: Unknown guide: FALSE
# Run `rlang::last_error()` to see where the error occurred.
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/767b0e88-1e49-1f5a-df93-afa2e42d0f32.png)
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/72d62bec-09af-893e-9186-effc029b5a2a.png)


##### guide_axis(), "axis"

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = "legend")
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  guides(x = guide_axis(), y = guide_axis(), color = "legend")
```

- https://qiita.com/swathci/items/00b4a847843a33345887#guide_axis軸の凡例を設定する関数
- https://qiita.com/swathci/items/00b4a847843a33345887#guide_axis軸の凡例を設定する関数-1

##### guide_legend(), "legend"

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = "legend")
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = guide_legend())

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = guide_legend(reverse = TRUE))
```

- https://qiita.com/swathci/items/00b4a847843a33345887#guide_legend凡例を設定する関数


##### guide_colorbar(), "colorbar"

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = "colorbar")
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = guide_colorbar())

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = guide_colorbar(reverse = TRUE))
```

- https://qiita.com/swathci/items/00b4a847843a33345887#guide_colorbarカラーバーを設定する関数


##### guide_bins(), "bins"

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = "bins")
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = guide_bins())

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = guide_bins(reverse = TRUE))
```

- https://qiita.com/swathci/items/00b4a847843a33345887#guide_bins


##### guide_coloursteps(), "colorsteps"

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = "colorsteps")
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = guide_colorsteps())

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Petal.Length)) +
  geom_point() +
  guides(x = "axis", y = "axis", color = guide_colorsteps(reverse = TRUE))
```

- https://qiita.com/swathci/items/00b4a847843a33345887#guide_coloursteps


#### scale_\*_\*()

`scale_color_*()`, `scale_fill_*()`で`color`, `fill`の凡例の設定がきます。

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  scale_color_discrete(name = "species",
                       labels = str_to_title(unique(iris$Species)))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/b23d82dc-4fdf-3af8-c0e4-bfd9e48b6bf7.png)

詳しくは[こちら](https://qiita.com/swathci/items/00b4a847843a33345887)参照。


# Zooming

```R:R
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  coord_cartesian(xlim = c(4, 6), ylim = c(2, 4))
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  xlim(4, 6) + ylim(2, 4)
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  scale_x_continuous(limits = c(4, 6)) + scale_y_continuous(limits = c(2, 4))
```
![plot.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/800718/3aab9535-b5fd-300d-60e3-35ad172f0992.png)


# Stats

`stat_*()`関数を使います。`stat_*()`関数については、[こちら](https://qiita.com/swathci/items/b08496d863bca4b479b3)にまとめました。


# 参考文献
- https://ggplot2.tidyverse.org/
- https://github.com/tidyverse/ggplot2
    - https://github.com/rstudio/cheatsheets/blob/master/data-visualization-2.1.pdf
- https://cran.r-project.org/web/packages/ggplot2/index.html
    - https://cran.r-project.org/web/packages/ggplot2/readme/README.html
- https://rstudio.cloud/learn/cheat-sheets
- https://ggplot2-book.org/index.html
    - https://ggplot2-book.org/toolbox.html
    - https://ggplot2-book.org/scales.html
- https://r-graphics.org/
- https://r4ds.had.co.nz/data-visualisation.html
    - https://r4ds.had.co.nz/graphics-for-communication.html
- https://heavywatal.github.io/rstats/ggplot2.html
- https://yukiyanai.github.io/jp/classes/stat2/contents/R/intro-to-ggplot2.html
- https://www.jaysong.net/RBook/
    - https://www.jaysong.net/RBook/visualization1.html
    - https://www.jaysong.net/RBook/visualization2.html
    - https://www.jaysong.net/RBook/visualization3.html
    - https://www.jaysong.net/RBook/visualization4.html
- https://kazutan.github.io/fukuokaR11/intro_ggplot2.html
- https://triadsou.hatenablog.com/entry/20100528/1275042816
- https://qiita.com/swathci/items/b08496d863bca4b479b3
- https://qiita.com/swathci/items/00b4a847843a33345887