ggplot2の使い方

基本的なプロット

#dataは一次元データを想定
par(family="HiraKakuProN-W3")
plot(data,type="p") #散布図
plot(data,type="l") #折れ線グラフ|lines()
barplot(data)       #棒グラフ
hist(res)           #ヒストグラム
boxplot(res)        #箱ヒゲ図
curve(x^2)          #関数曲線をプロット

共通オプション

ggsave("test.png")
+ xlab("Xname") + ylab("Yname)
+ xlim(1,10) + ylim(2,20)
+ stat_smooth(method=lm,se=FALSE)
+ coord_flip() #x,y反転
+ theme_bw() #テーマ変更
+ facet_grid(fac~.) #y軸分割
+ facet_grid(.~fac) #x軸分割
+ guides(fill=FALSE) #塗りの凡例削除
+ theme_gray(base_family="HiraKakuProN-W3")
#カラーパレットの表示
library(RColorBrewer)
display.brewer.all()

棒グラフ

#通常の棒グラフ
ggplot(dat,aes(x=ID,y=res))+geom_bar(stat="identity")
#カラーの指定
ggplot(dat,aes(x=ID,y=res))+geom_bar(stat="identity",fill="lightblue",colour="black")
#棒グラフの軸が連続値で欠損が見られるところをカテゴリかる変数に変換する
ggplot(dat,aes(x=factor(ID),y=res))+geom_bar(stat="identity")
#棒をグループ化する,fill指定で色を分けることができる
ggplot(dat,aes(x=ID,y=res,fill=Cultivar))+geom_bar(stat="dodge")

折れ線グラフ

#通常の折れ線グラフ
ggplot(dat,aes(x=ID,y=res))+geom_line()+geom_point()
#積み上げグラフの作成
library(gcookbook) #sample data
ggplot(uspopage,aes(x=Year,y=Thousands,fill=AgeGroup))+geom_area()

#点 + 点線プロット
p<-ggplot(dat,aes(x=ID,y=res,label=res))+geom_line(linetype="dashed",colour="grey")+geom_point(aes(fill=res),size=3,shape=21)+xlab("packet division")+ylab("transmission delay")+ggtitle("Transmission Delays")+geom_text(aes(y=res+1.1),size=3)
print(p+scale_fill_distiller(palette="Greys")+guides(fill=FALSE))

散布図

ggplot(dat,aes(x=Year,y=Height,colour=sex))+geom_point()

ネットワークグラフ

library(igraph)
set.seed(123)
gd<-graph(c(1,2, 2,3, 2,4, 1,4, 5,5, 3,6))

テキストプロット

ggplot(meisi,aes(x=x,y=y,label=Term))+geom_text(family="HiraKakuProN-W3",size=3)+xlab("タイトル")

Melt

参考資料