我想在一个 4×4 网格中比较两个文件的数据。数据文件如下:
data1.dat
:
A B C D
.....
data2.dat
:
1 2 3 4
.........
我能够使用来自此站点的代码片段通过以下代码设置网格。必须手动输入每个网格点的标签。我想要一些建议来修改程序以从文件中读取标签。
\documentclass{article}
\usepackage{tikz}
\begin{filecontents}{Data1.dat}
A B C D
E F G H
I J K L
M N O P
\end{filecontents}
\begin{filecontents}{Data2.dat}
1 2 3 4
5 6 7 8
9 10 11 12
11 12 13 14
\end{filecontents}
\begin{document}
\begin{tikzpicture}
\draw[step=1.0cm,color=gray] (-2,-2) grid (2,2);
\node at (-1.5,+1.75) {A};
\node at (-1.5,+1.25) {1};
\node at (-0.5,+1.75) {B};
\node at (-0.5,+1.25) {2};
\node at (+0.5,+1.75) {C};
\node at (+0.5,+1.25) {3};
\node at (+1.5,+1.75) {D};
\node at (+1.5,+1.25) {4};
%..
\node at (+1.5,-1.25) {P};
\node at (+1.5,-1.75) {16};
\end{tikzpicture}
\end{document}
答案1
概念证明;这个想法是使用pgfplotstable
;排版第一个表,适当地为第二个表的值保留空间;然后,排版第二个表并叠加到第一个表,使用简单的\llap
:
\documentclass{article}
\usepackage{pgfplotstable}
\newcolumntype{C}{>{\centering\arraybackslash\rule{0pt}{15pt}}p{2em}}
\pgfplotstableread{%
1 2 3 4
5 6 7 8
9 10 11 12
11 12 13 14
}{\loadedtablei}
\pgfplotstableread{
A B C D
E F G H
I J K L
M N O P
}{\loadedtableii}
\begin{document}
\pgfplotstabletypeset[%
header=false,
every head row/.style={before row=\hline},
every first row/.style={before row= & & & \\\hline},
every nth row={1}{before row= & & & \\\hline},
every last row/.style={after row= & & & \\\hline},
display columns/0/.style={string type,column type=|C},
display columns/1/.style={string type,column type=|C},
display columns/2/.style={string type,column type=|C},
display columns/3/.style={string type,column type=|C|}
]{\loadedtableii}%
\llap{%
\pgfplotstabletypeset[
header=false,
columns/0/.style={column type=|C},
columns/1/.style={column type=|C},
columns/2/.style={column type=|C},
columns/3/.style={column type=|C|},
every head row/.style={output empty row,before row=\multicolumn{4}{c}{}\\[2ex]},
every first row/.style={before row=,after row=& & & \\},
every nth row={1}{after row=& & & \\},
every last row/.style={output empty row,after row=\multicolumn{4}{c}{}},
]{\loadedtablei}%
}
\end{document}
答案2
您可以使用pgfplotstable
这个来获取特定行列的元素,但是如果这是您的真实示例,那么您可以在没有表格的情况下得出相应的大写字母。但我想这是一个简化的情况。
\documentclass{article}
\usepackage{pgfplotstable}%<-loads TikZ and pgfplots anyway
\pgfplotstableread[header=false]{
A B C D
E F G H
I J K L
M N O P
}\firsttable
\pgfplotstableread[header=false]{
1 2 3 4
5 6 7 8
9 10 11 12
11 12 13 14
}\secondtable
\begin{document}
\begin{tikzpicture}
\draw[step=1.0cm,color=gray] (-2,-2) grid (2,2);
\foreach\x[evaluate=\x as \xi using int(\x-1)] in {4,...,1}{
\foreach\y[evaluate=\y as \yi using int(4-\y)] in {1,...,4}{
\pgfplotstablegetelem{\yi}{[index]\xi}\of\firsttable
\node (nup-\x-\y) at ({(2*\x-1)/2-2},{(2*\y-1)/2-2+0.25}) {\pgfplotsretval};
\pgfplotstablegetelem{\yi}{[index]\xi}\of\secondtable
\node (ndown-\x-\y) at ({(2*\x-1)/2-2},{(2*\y-1)/2-2-0.25}) {\pgfplotsretval};
}
}
\end{tikzpicture}
\end{document}