R:我们如何绘制棋盘(N×N)网格?

时间:2015-12-06 23:25:25

标签: r csv plot ggplot2

如果我有这样的CSV:

row,column
1,0
5,1
7,2
2,3
0,4
3,5
6,6
4,7

8x8 Chessboard

CSV数据中填充的黑色方块会产生:

Populated 8x8 Chessboard

我在底层地块上绘制黑色方块。无法在右侧部分获得黑色方块。我还是R新手,所以我遇到了一些困难。我哪里错了?

library(data.table)

library(reshape2)
library(ggplot2)

data_csv <- fread('./data.csv')

mx <- matrix(data_csv, nrow=8, ncol=8)

ggplot(melt(mx), aes(x=Var1, y=Var2)) + geom_tile()

尝试将其设置为动态,以便在CSV增长到n行时,它仍会处理。

1 个答案:

答案 0 :(得分:6)

首先阅读数据:

chessdat <- read.table(text='row,column
1,0
5,1
7,2
2,3
0,4
3,5
6,6
4,7', sep =',', header = T)

因为geom_tile位于该点的中心,所以让我们给出一个偏移量

offset <- 0.5
chessdat2 <- chessdat + offset

然后按照你的方式进行策划:

ggplot(chessdat2, aes(row,column)) + geom_tile() + theme_bw()

给出了:

enter image description here

然后再玩一下格式,我们就可以到达棋盘了:

ggplot(chessdat2, aes(row,column)) + geom_tile() + 
     theme_bw() + 
     theme(panel.grid.major = element_line(size = 2, color='black'),       
     panel.grid.minor = element_line(size=2, color = 'black'),
     axis.ticks = element_blank(), 
     axis.text = element_blank(), 
     axis.title = element_blank()) + 
     coord_cartesian(xlim=c(0,8), ylim=c(0,8))

给出了情节:

enter image description here