下面我们展示3个版本。第一个使用正方形,下一个使用圆形,下一个使用一个男人的图标,最后我们使用笑脸。
正方形
# input data
set.seed(123)
x <- sample(c("A","B"),100,replace = T)
# input parameters - nr * nc should equal length(x)
cols <- c("green", "red")
nr <- 10
nc <- 10
# create data.frame of positions and colors
m <- matrix(cols[factor(x)], nr, nc)
DF <- data.frame(row = c(row(m)), col = c(col(m)[, nc:1]), value = c(m),
stringsAsFactors = FALSE)
# plot squares - modify cex to get different sized squares
plot(col ~ row, DF, col = DF$value, pch = 15, cex = 4, asp = 1,
xlim = c(0, nr), ylim = c(0, nc),
axes = FALSE, xlab = "", ylab = "")

界
# plot circles
plot(col ~ row, DF, col = DF$value, pch = 20, cex = 6, asp = 1,
xlim = c(0, nr), ylim = c(0, nc),
axes = FALSE, xlab = "", ylab = "")

png Icons此解决方案使用一个人的黑白图标,我们假设该图标已保存在当前目录中为man.png
. 我们将其着色为红色和绿色,并使用这两个版本代替正方形或圆形:
# blank graph to insert man icons into
plot(col ~ row, DF, col = DF$value, asp = 1,
xlim = c(0, nr), ylim = c(0, nc),
axes = FALSE, xlab = "", ylab = "", type = "n")
library(png)
man <- readPNG("man.png")
red.man <- man
red.man[,,1] <- man[,,4] # fill in red dimension
R <- subset(DF, value == "red")
with(R, rasterImage(red.man,
row-.5, col-.5, row+.5, col+.5,
xlim = c(0, nr), ylim = c(0, nc),
xlab = "", ylab = ""))
green.man <- man
green.man[,,2] <- man[,,4] # fill in green dimension
G <- subset(DF, value == "green")
with(G, rasterImage(green.man,
row-.5, col-.5, row+.5, col+.5,
xlim = c(0, nr), ylim = c(0, nc),
xlab = "", ylab = ""))

笑脸图标此解决方案使用绿色笑脸图标和红色皱眉脸图标,我们假设它们已保存在当前目录中,分别为smiley_green.jpg
和smiley_red.jpg
。
# blank graph to insert man icons into
xp <- 1.25
plot(col ~ row, DF, col = DF$value, asp = 1,
xlim = c(0, xp * nr), ylim = c(0, xp * nc),
axes = FALSE, xlab = "", ylab = "", type = "n")
library(jpeg)
smiley_green <- readJPEG("smiley_green.jpg")
smiley_red <- readJPEG("smiley_red.jpg")
R <- subset(transform(DF, row = xp * row, col = xp * col), value == "red")
with(R, rasterImage(smiley_red,
row - .5, col - .5, row + .5, col + .5,
xlim = c(0, xp * nr), ylim = c(0, xp * nc),
xlab = "", ylab = ""))
G <- subset(transform(DF, row = xp * row, col = xp * col), value == "green")
with(G, rasterImage(smiley_green,
row - .5, col - .5, row + .5, col + .5,
xlim = c(0, xp * nr), ylim = c(0, xp * nc),
xlab = "", ylab = ""))

修改为 10x10 绿色/红色并添加了使用人图标的版本。