Skip to content

Instantly share code, notes, and snippets.

@m-note
Last active September 18, 2015 06:35
Show Gist options
  • Save m-note/5f80f4719c0e51bf1608 to your computer and use it in GitHub Desktop.
Save m-note/5f80f4719c0e51bf1608 to your computer and use it in GitHub Desktop.
ggplot2で折れ線グラフ + 複数のグラフを並べる
library(ggplot2)
library(reshape2) # melt()用
library(grid) ; library(gridBase) # 複数の図の配置 cf. http://d.hatena.ne.jp/dichika/20110116/1295183973
country_list = c("Egypt", "Armenia",
"Afghanistan", "Azerbaijan", "Bosnia", "Cambodia", "Croatia",
"Eritrea", "Kazakhstan", "South Africa", "Vietnam")
for (country in country_list){
aid_amount <- AidData[AidData$recipient==country, c("Aid_All", "year", "p4_polity2", "Giniall")] # 全ての援助額
# ggplot2 描画レイヤー /AidAll
g <- ggplot(
aid_amount,
aes(
x = year,
y = Aid_All,
#group = id,
#colour = type
)
)
g <- g + geom_line()
g <- g + theme_bw() # 白色背景に灰色グリッドのテーマ
g <- g + theme(axis.text.x = element_text(size=12),
axis.title.x = element_text(size=15),
axis.text.y = element_text(size=12),
axis.title.y = element_text(size=15),
axis.ticks.y = element_blank(),
plot.title = element_text(size = rel(1.4))) # グラフタイトルのサイズ
g <- g + labs(title = paste(country, ": Aid_All", sep=""))
# ggplot2 描画レイヤー / Polity and Inequality
aid_amount <- AidData[AidData$recipient==country, c("Aid_All", "year", "p4_polity2", "Giniall")] # 全ての援助額
aid_amount$Giniall <- aid_amount$Giniall / 10 # rescale
aid_amount <- melt(aid_amount, id="year", measure=c("Giniall", "p4_polity2")) # ggplot用に変形
g2 <- ggplot(aid_amount,
aes(x=year,
y=value,
colour=variable,
group=variable)) + geom_line()
#g2 <- g2 + guides(colour = guide_legend(reverse = TRUE)) # 凡例の順番を合わせる
g2 <- g2 + scale_colour_discrete(name="Values", # colour, fill, shapeの使い分けがよくわからず。今回は線に対応してだったからcolour?
# cf.http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/
breaks=c("Giniall", "p4_polity2"),
labels=c("Inequality(Gini)", "Polity"))
g2 <- g2 + labs(title = country, x="year", y="values")
g2 <- g2 + theme_bw() # 白色背景に灰色グリッドのテーマ
filename = paste("AidAllGraph_", country, ".pdf", sep = "")
pdf(filename,width=10,height=4.25)
#plot.new()
# 複数グラフの描画 cf. http://d.hatena.ne.jp/dichika/20110116/1295183973 4分割なども可能
grid.newpage() #空の画面を作る
pushViewport(viewport(layout=grid.layout(1, 2))) #画面を区切る(今回は1行2列の2分割)
print(g, vp=viewport(layout.pos.row=1, layout.pos.col=1)) #1行目の1列
print(g2, vp=viewport(layout.pos.row=1, layout.pos.col=2) ) #1行目の2列
dev.off()
} #close for(country)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment