ggplot2を用いたグラフの作成

サンプルで使うデータ

  • ggplot2パッケージのdiamondsデータセット
ggplot2::diamonds

テーマの設定

  • ggplot2::theme_set で、出力する全てのグラフに一括してテーマを適用できる
    • テーマの種類(以下ではtheme_bw()を適用)、フォントの種類や大きさを指定しておくと良い
ggplot2::theme_set(
  ggplot2::theme_bw(
    base_size = 12,
    base_family = "BIZ UDGothic")
  )

1次元の棒グラフ

  • ggplot2::geom_bar
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_bar(
    ggplot2::aes(color)
  )

1次元ヒストグラム

  • ggplot2::geom_histogram
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_histogram(
    ggplot2::aes(price)
  )
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

2次元ヒストグラム

  • ggplot2::geom_bin_2d
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_bin_2d(
    ggplot2::aes(price, carat)
  )

箱ひげ図

  • ggplot2::geom_boxplot
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_boxplot(
    ggplot2::aes(color, price)
  ) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )

軸を入れ替える

  • ggplot2::coord_flip
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_boxplot(
    ggplot2::aes(color, price)
  ) +
  ggplot2::labs(
    title = "価格とカラット数", #タイトル
    x = "カラット数",
    y = "価格"
  ) +
  ggplot2::coord_flip()

折れ線グラフ

  • ggplot2::geom_line
ggplot2::economics |> 
  ggplot2::ggplot() +
  ggplot2::geom_line(
    ggplot2::aes(date, pop)
  ) +
  ggplot2::coord_cartesian(
    ylim = c(0, 400000)
  ) +
  ggplot2::labs(
    x = "日付", y = "人口"
  )

散布図

  • ggplot2::geom_point()
    • x軸やy軸に使うデータなどは、引数の中にaes関数を記述することで指定できる
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_point(
    ggplot2::aes(carat, price)
  ) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )

軸の範囲指定

  • ggplot2::coord_cartesian を使う
  • ggplot2::limsやggplot2::xlim, ggplot2::ylim は使わない
    • 範囲外のデータを無視して分析してしまうことになるので
      • 回帰直線を引く際に支障が出る
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_point(
    ggplot2::aes(carat, price)
  ) +
  ggplot2::coord_cartesian(
    xlim = c(0, 1),
    ylim = c(0, 10000)
  ) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )

グループごとに色分け

  • グループごとに色分けをするためには、aes関数内のcolorオプションで、グループ分けの基準となる列を指定
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_point(
    ggplot2::aes(carat, price, color = color), 
  ) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )

変数に基づく、点の大きさの指定

  • aes関数内のsizeオプション
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_point(
    ggplot2::aes(carat, price, color = color, size = clarity), 
  ) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )

回帰直線を加える

  • ggplot2::stat_smooth
    • method オプションで、回帰分析の種類を表す関数を指定できる
      • デフォルトはglm
      • 例えばロジスティック回帰の場合は、method.args = list(family = “binomial”) のようにオプションを追加で指定すれば対応可能
    • se = FALSE を指定すれば信頼区間を表示しないようにできる
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::aes(carat, price) +
  ggplot2::geom_point() +
  ggplot2::stat_smooth(
    method = lm, # lm関数で推定
    se = FALSE # 信頼区間は表示しない
  ) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )
`geom_smooth()` using formula = 'y ~ x'

グループごとにグラフ作成

  • ggplot2::facet_wrap
    • 引数内の変数名は、ggplot2::vars()の引数に入れる
ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_point(
    ggplot2::aes(carat, price), 
  ) +
  ggplot2::facet_wrap(color |> ggplot2::vars()) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )

グラフの保存

  • ggplot2::ggsave 関数を用いればグラフの保存が可能
    • プロットは、デフォルトでは直近に出力されたものが指定される
    • plot オプションで指定可能
      • ggplot の処理ごと変数に格納しておく!
plot <- ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_point(
    ggplot2::aes(carat, price)
  ) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )

ggplot2::ggsave("plot.png", plot = plot)

グラフ内のクリック操作を可能にする

  • plotly::ggplotly をggplotに適用すれば、グラフ内のクリック操作が可能に
  • plotly::toWebGL() を上記に加えると、描画が高速になる
plot <- ggplot2::diamonds |> 
  ggplot2::ggplot() +
  ggplot2::geom_point(
    ggplot2::aes(carat, price, color = color), 
  ) +
  ggplot2::labs(
    x = "カラット数", y = "価格"
  )

plot |> 
  plotly::ggplotly() |> 
  plotly::toWebGL()
Warning: 'scattergl' objects don't have these attributes: 'hoveron'
Valid attributes include:
'connectgaps', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'fill', 'fillcolor', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Warning: 'scattergl' objects don't have these attributes: 'hoveron'
Valid attributes include:
'connectgaps', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'fill', 'fillcolor', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Warning: 'scattergl' objects don't have these attributes: 'hoveron'
Valid attributes include:
'connectgaps', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'fill', 'fillcolor', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Warning: 'scattergl' objects don't have these attributes: 'hoveron'
Valid attributes include:
'connectgaps', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'fill', 'fillcolor', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Warning: 'scattergl' objects don't have these attributes: 'hoveron'
Valid attributes include:
'connectgaps', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'fill', 'fillcolor', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Warning: 'scattergl' objects don't have these attributes: 'hoveron'
Valid attributes include:
'connectgaps', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'fill', 'fillcolor', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

Warning: 'scattergl' objects don't have these attributes: 'hoveron'
Valid attributes include:
'connectgaps', 'customdata', 'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'fill', 'fillcolor', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'selected', 'selectedpoints', 'showlegend', 'stream', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'unselected', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xhoverformat', 'xperiod', 'xperiod0', 'xperiodalignment', 'xsrc', 'y', 'y0', 'yaxis', 'ycalendar', 'yhoverformat', 'yperiod', 'yperiod0', 'yperiodalignment', 'ysrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

クリック操作でのグラフ作成

  • esquisseパッケージのesquisser関数が便利
ggplot2::diamonds |> 
  esquisse::esquisser()
  • 変数名をドラッグして使用するデータを選択したり、表題や軸ラベルを変更できる
  • 完成できたら、“Code” → “Insert code in script” をクリック