ねこすたっと

ねこの気持ちと統計について悩む筆者の備忘録的ページ。

1つのカテゴリー変数をグラフにする(ggplot2パッケージ)[R]

ggplot2パッケージ(tidyverseパッケージに含まれている)のdiamondsデータを使う。

> library(tidyverse)
> head(diamonds)
# A tibble: 6 x 10
  carat cut       color clarity depth table price     x     y     z
  <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.31 Good      E     SI1      63.3  55     544  4.33  4.36  2.75
2  0.8  Very Good H     VS2      59.1  59    2953  6.02  6.07  3.57
3  0.78 Very Good H     VS1      61.9  57.1  2854  5.87  5.95  3.66
4  0.3  Ideal     G     VVS2     61.5  57     684  4.29  4.33  2.65
5  1.5  Good      F     SI2      59.7  61    8181  7.39  7.44  4.43
6  1.2  Very Good E     SI2      61.4  58    6130  6.81  6.88  4.2 
  • carat:重さ(カラット)
  • cut:カットの質(5段階)
  • color:色(7段階)
  • clarity:透明度(8段階)
  • depth \frac{2z}{(x+y)}
  • table:最も幅広い部分に対する最上部の幅
  • price:値段(USD)
  • x, y, z:それぞれ長さ・幅・高さ(mm)

geom_bar( )を使って棒グラフを描く

カットの質(cut)のカテゴリー別度数を棒グラフとして表示する。

ggplot(data = diamonds, aes(x = cut)) +
  geom_bar()

図1:棒グラフ

geom_bar( )の引数を指定する

※ 線については以前まとめた記事があります(2022-07-17 追加)

necostat.hatenablog.jp

以下、指定例。

ggplot(data = diamonds, aes(x = cut)) +
  geom_bar(fill = "royalblue",
           alpha = 0.5, 
           colour = "navy", 
           linetype = 2,
           size = 0.5)

図2:色・線種などを指定した

stat_count( )との対応

「データの集計方法」と「グラフの形状」は密接に関連していて、棒グラフで表すとき(geom_bar())は各カテゴリーの合計数(stat_count())が対応している。geom_*stat_*のどちらを先に指定しても良い。
下の3つのコードは前述のものと同じ棒グラフを出力する。(geom_bar()のときはstat="count"がデフォルトなので省略可。逆も同じ。)

ggplot(data = diamonds, aes(x = cut)) +
  geom_bar(stat = "count")

ggplot(data = diamonds, aes(x = cut)) +
  stat_count(geom = "bar")

ggplot(data = diamonds, aes(x = cut)) +
  stat_count()

おわりに

  • geom*とstat*の関係を知ってからggplotの文法が少し分かるようになりました
  • 寒くなってきてネコが布団に入ってきてくれるんじゃないかと期待

参考資料

  • 本家ページ:

ggplot2.tidyverse.org

  • geom_*stat_*の関係が詳しくまとめられています

ggplot2のstat_*()関数についてのまとめ - Qiita