LoginSignup
12
9

More than 5 years have passed since last update.

ggplotとqplotの対応

Last updated at Posted at 2015-04-23

https://github.com/hadley/ggplot2/blob/master/R/translate-qplot-ggplot.r
に、ggplotとqplotの対応が書いてあったので、適当に訳してみた。以下はその内容。

Translating between qplot and ggplot

ggplot2の中には2種類のplotを作る関数がある。それは

  • qplot()
  • ggplot()

である。
qplotは、手軽に使えるようにするために、幾つもの仮定をおいていて、大抵はより素早くplotをかけるが、複数のレイヤやデータを使うような複雑なプロットをするときはうまくいかない。

ここでは、このqplotが仮定しているデフォルトの挙動は何か、ggplotと例を上げて比較することで示す。

基礎

qplotはデフォルトで散布図(scatterplot)を仮定する。

qplot(x, y, data = data)
ggplot(data, aes(x, y)) + geom_point()

Aesthetics(aes)を使う

ここでは Aesthetic を データ系列と訳すことにする

なお、qplotは違うレイヤの審美値マッピングやデータを使う方法はない。

qplot(x, y, data = data, shape = shape, colour = colour)
ggplot(data, aes(x, y, shape = shape, colour = colour)) + geom_point()
ggplot(data, aes(x)) + geom_bar()
qplot(x, data = data, geom = "bar")

geom属性を変えたいときはgeomパラメータを変更する。

qplot(x, y, data = data, geom = "line")
ggplot(data, aes(x, y)) + geom_line()

geomによっては、x,yの両方を必要としない。具体的には、geom_bar()geom_histogram()である。
yが与えられなかった場合、qplotもggplotもxを"count"した結果をyとして使う。

qplot(x, data = data, geom = "bar")
ggplot(data, aes(x)) + geom_bar()

geomの引数にgeom名の配列が渡された場合は、その順番にgeomが追加されていく。

qplot(x, y, data = data, geom = c("point", "smooth"))
ggplot(data, aes(x, y)) + geom_point() + geom_smooth()

ggplot2の他のところとは違い、statとgeomは独立している。

qplot(x, y, data = data, stat = "bin")
ggplot(data, aes(x, y)) + geom_point(stat = "bin")

layerのパラメータは全てのレイヤに渡される。ほとんどのレイヤはそのパラメータが必要ないため、そのパラメータ情報が無視される。

qplot(x, y, data = data, geom = c("point", "smooth"), method = "lm")
ggplot(data, aes(x, y)) + geom_point(method = "lm") + geom_smooth(method = "lm")

スケールと軸

x, yのスケールは、xlim, ylim, xlab, ylabを用いて設定できる。

qplot(x, y, data = data, xlim = c(1, 5), xlab = "my label")
ggplot(data, aes(x, y)) + geom_point() +
scale_x_continuous("my label", limits = c(1, 5))
qplot(x, y, data = data, xlim = c(1, 5), ylim = c(10, 20))
ggplot(data, aes(x, y)) + geom_point() +
scale_x_continuous(limits = c(1, 5)) + scale_y_continuous(limits = c(10, 20))

plotと同様にqplotは、簡単に軸をlogスケールに変換する事ができる。

qplot(x, y, data = data, log = "xy")
ggplot(data, aes(x, y)) + geom_point() + scale_x_log10() + scale_y_log10()

ggplotはもっと多彩なスケール変換ができるが、qplotの中からその全てにアクセスできるわけではない。詳細はscale_continuous参照。

Plotのオプション

qplotはplotと同じオプションをとることができ、対応するggplot2のオプションに変換される. 以下の例ではmainaspオプションが変換されている。

qplot(x, y, data = data, main="title", asp = 1)
ggplot(data, aes(x, y)) + geom_point() + labs(title = "title") + theme(aspect.ratio = 1)
12
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9