2015-12-06 91 views
3

如果我有一个CSV这样:R:我们如何绘制棋盘(N乘N)网格?

Populated 8x8 Chessboard

矿借鉴了底层情节黑色正方形:

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

8x8 Chessboard

填充的黑色从CSV数据结果平方。无法在右侧获得黑色方块。我还是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线,它仍将处理。

回答

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