まずはデフォルトのthemeで散布図を作成。
ちなみに、デフォルはのtheme_grey()
になってます。
> library(ggplot2)
> scatter <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width))
> scatter + geom_point(aes(color=Species, shape=Species)) +
+ xlab("Sepal Length") + ylab("Sepal Width") +
+ ggtitle("Sepal Length-Width")

コード上でthemeを変更してみる。
> library(ggplot2)
> scatter <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width))
> scatter + geom_point(aes(color=Species, shape=Species)) +
+ xlab("Sepal Length") + ylab("Sepal Width") +
+ ggtitle("Sepal Length-Width")
+ theme_bw() +
+ theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = "black", size=12),
+ plot.title = element_text(size=24, face="bold", hjust=0.5))

theme_bw()でテーマが変更された後、
タイトルが大きくなって、X軸の補助目盛りが斜めになっている。
ただ、毎回themeを書くのが面倒くさそう。
そういう場合は、自分のthemeを作成するのが良さそう。
## 例①
> library(ggplot2)
> theme_me <- theme_bw() +
+ theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = "black", size=12),
+ plot.title = element_text(size=24, face="bold", hjust=0.5))
> scatter <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width))
> scatter + geom_point(aes(color=Species, shape=Species)) +
+ xlab("Sepal Length") + ylab("Sepal Width") +
+ ggtitle("Sepal Length-Width") +
+ theme_me
## 例② theme_meをfunctionで定義する
> theme_me <- function() { theme_bw() +
+ theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = "black", size=12),
+ plot.title = element_text(size=24, face="bold", hjust=0.5))
+ }
> scatter <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width))
> scatter + geom_point(aes(color=Species, shape=Species)) +
+ xlab("Sepal Length") + ylab("Sepal Width") +
+ ggtitle("Sepal Length-Width") +
+ theme_me()

どちらのコードも新しいテーマが散布図に当たるようになる
例②の方が他のthemeと同じように使えるので、個人的には好み。
- デフォルのテーマを変更したい場合
## 例①の場合
> theme_set(theme_me)
## 例②の場合
> theme_set(theme_me())
## themeを変更せずに、カスタマイズしたテーマが散布図に反映される。
> scatter <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width))
+ scatter + geom_point(aes(color=Species, shape=Species)) +
+ xlab("Sepal Length") + ylab("Sepal Width") +
+ ggtitle("Sepal Length-Width")

お洒落なテーマをカスタマイズして、デフォルトに設定しておくと良さそうだけど、
どこかに落ちてないかな。。