ウォーホルのアレっぽいものを作ってみる

ggplot2のテーマ練習がてら。画像がつぶれてもうた上になんか全然違うけどまあよい。もう少しよくする。


コードは以下の通り。

library(ReadImages)
library(ggplot2)
data <- read.jpeg("maririn.jpg") #画像ファイルを指定
data #imagematrixに変換されている
data <- rgb2grey(data) #グレースケールに変換
d <- data.frame(matrix(data, ncol=298)) #データフレームに変換する際に行列の列を指定
d$id <- row.names(d)
dm <- melt(d)
colnames(dm) <- c("row","col","grey")
dm$row <- as.numeric(dm$row)*(-1)
dm$col <- as.numeric(gsub("X", "", dm$col))
dm$grey <- -(dm$grey - 1)

#画面をフルに使うために各種テーマをいじる
theme_update(legend.position = "none",
    panel.margin = unit(0,"null"),
    plot.margin = rep(unit(0,"null"),4),
    axis.ticks = theme_blank(),
    axis.text.x = theme_blank(),
    axis.text.y = theme_blank(),
    axis.title.x = theme_blank(),
    axis.title.y = theme_blank(),
    axis.ticks.length = unit(0,"null"),
    axis.ticks.margin = unit(0,"null")
  )

p1 <- ggplot(data=dm, aes(x=col, y=row)) + geom_tile(aes(fill=grey)) + scale_fill_gradient(low="black", high="white") 
p2 <- ggplot(data=dm, aes(x=col, y=row)) + geom_tile(aes(fill=grey)) + scale_fill_gradient(low="pink", high="blue")
p3 <- ggplot(data=dm, aes(x=col, y=row)) + geom_tile(aes(fill=grey)) + scale_fill_gradient(low="green", high="yellow")
p4 <- ggplot(data=dm, aes(x=col, y=row)) + geom_tile(aes(fill=grey)) + scale_fill_gradient(low="red", high="blue")

png("maririn.png")
grid.newpage()
pushViewport(viewport(layout=grid.layout(2,2)))
print(p1, vp=viewport(layout.pos.row=1, layout.pos.col=1))
print(p2, vp=viewport(layout.pos.row=1, layout.pos.col=2))
print(p3, vp=viewport(layout.pos.row=2, layout.pos.col=1))
print(p4, vp=viewport(layout.pos.row=2, layout.pos.col=2))
dev.off()

参考

テーマの調節は以下を参考にした。
https://kohske.wordpress.com/2010/12/25/drawing-on-full-region-in-ggplot2/