ggplot2はデータフレームから作図する。

はじめにインポートする。

library(ggplot2)

以下の例では、データとしてirisを使うものとする。

グラフはレイヤーを加算して描かれる。

ggplot(データ等) + geom_グラフ種類()

をベースとして、タイトル・軸・凡例・背景などの要素が+で加算される。

散布図

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

バイオリンプロット

ggplot(iris, aes(x=Petal.Width, y=Petal.Length, color=Species)) + geom_violin()

箱ひげ図

ggplot(iris, aes(x=Petal.Width, y=Petal.Length, color=Species)) + geom_boxplot()

ヒストグラム

ggplot(iris, aes(x=Petal.Length, color=Species)) + geom_histogram(fill = "gold")

カーネル密度推定

ggplot(iris, aes(x=Petal.Length, color=Species)) + geom_density()

タイトル

labs(title="タイトル", subtitle="サブタイトル")

日本語を使うなら、ggplot2のインポート後、文字化け解消に次を書いておく。

theme_set(theme_bw(base_family = "HiraKakuProN-W3"))

画像の保存

ggsave(filename = "保存ファイル名.png",
plot = ggplotしたグラフ,
device = "png",
scale = 1,
width = 10,
height = 10,
units = c("in"),
dpi = 1200)