目次

ggplot2 {R}

グラフの形の指定方法

geom_density()
密度
geom_histogram()
ヒストグラム
geom_boxplot()
箱ひげ図
geom_bar()
棒グラフ(データのカウントをする)
geom_col()
棒グラフ(データの数を集計させず生データのまま縦軸にする)
geom_point()
散布図
geom_jitter()
重なる点を横に広げる

軸ラベルの指定方法

+ labs("タイトルラベル", "X軸ラベル", "Y軸ラベル")
ggplot(msleep, aes(X, Y) +   #ggplotで読み込むデータセット,x軸,y軸指定
  geom_point(aes(shape=Z, color=Z)) +    #散布図を指定,形と色を決める変数も指定
  labs(title = "XとYの関係",   #タイトルの指定
       x = "X[(kg)]",        #x軸ラベルの指定
       y = "Y[時間]")         #y軸ラベルの指定

軸ラベルを回転させて重ならなくする

+scale_x_discrete(guide = guide_axis(angle=45))

凡例の編集

scale_color_discrete(
  name ="その凡例ラベルの名前"  #diamond の例であれば clarity など
  labels ="それぞれのカテゴリに対応した名前"  #clarity だと I1,SI2,SI1,VS2,VS1,VVS2,VVS1,IFの7段階
  breaks ="上記のカテゴリのレベル"           #どの順で提示するかを指定する
  )

凡例ラベルを削除する

+ scale_fill_discrete(guide = FALSE)

Themeを指定する

+theme_bw()
+theme_classic()
+theme_dark()
+theme_gray()
+theme_light()
+theme_linedraw()
+theme_minimal()
install.packages("ggthemes")
library(ggthemes)

凡例の位置を調整する

+ theme(legend.position = "bottom")   #凡例を下に
+ theme(legend.position = "right")    #凡例を右に(初期設定)
+ theme(legend.position = "top")      #凡例を上に
+ theme(legend.position = "left")     #凡例を左に
+ theme(legend.position = c(1,1))      #凡例を右上に
+ theme(legend.position = c(0.5,0.5))  #凡例をグラフのど真ん中に(邪魔)
+ theme(legend.position = c(0,0))      #凡例を左下に

具体例

散布図の具体例

ggplot(data = diamonds) + 
  geom_point(
    mapping = aes(x = carat,y = price,color = color)
  )

gg <- ggplot(diamonds, aes(carat, price))
gg + geom_point(aes(color = cut))

箱ひげ図

gg <- ggplot(diamonds, aes(color, price))
gg + geom_boxplot(aes(fill=clarity, color = clarity))