以下 MWE 取自这里。
我有一个相关矩阵,为了简单起见,我想将上三角留空。但是,当我这样做时,代码会中断(可能是因为 if 语句)。
我需要如何调整代码以允许空单元格?
\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{pgfplotstable}
\pgfplotstableset{
color cells/.style={
col sep=comma,
string type,
postproc cell content/.code={%
\pgfkeysalso{@cell content=\rule{0cm}{2.4ex}%
\pgfmathtruncatemacro\number{##1}%
\ifnum\number<0
\cellcolor{red!-##1}##1
\else
\cellcolor{green!##1}##1
\fi
}},
columns/x/.style={
column name={},
postproc cell content/.code={}
}
}
}
\begin{document}
\begin{table}\caption{Correlation or something}
\centering
\pgfplotstabletypeset[color cells]{
x,a,b,c,d
a,90,-10.5,0,0
b,0,80,10,-10
c,0,0,-95,5
d,0,10,5,-85
}
\end{table}
\end{document}
答案1
您还可以测试单元格内容是否为空
\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.15}
\usepackage{etoolbox}
\pgfplotstableset{
color cells/.style={
col sep=comma,
string type,
postproc cell content/.code={%
\pgfkeysalso{@cell content=\rule{0cm}{2.4ex}%
\ifstrequal{##1}{}{}{%
\pgfmathtruncatemacro\number{##1}%
\ifnum\number<0
\cellcolor{red!-##1}##1
\else
\cellcolor{green!##1}##1
\fi}%
}},
columns/x/.style={
column name={},
postproc cell content/.code={}
}
}
}
\begin{document}
\begin{table}\caption{Correlation or something}
\centering
\pgfplotstabletypeset[color cells]{
x,a,b,c,d
a,90,,,
b,0,80,,
c,0,0,-95,
d,0,10,5,-85
}
\end{table}
\end{document}
结果:
或者您可以测试单元格内容是否为数字:
\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.15}
\usepackage{scrbase}
\pgfplotstableset{
color cells/.style={
col sep=comma,
string type,
postproc cell content/.code={%
\pgfkeysalso{@cell content=\rule{0cm}{2.4ex}%
\ifisdimension{##1 pt}{%
\ifdim ##1 pt<0pt
\cellcolor{red!-##1}##1
\else
\cellcolor{green!##1}##1
\fi}{}%
}},
columns/x/.style={
column name={},
postproc cell content/.code={}
}
}
}
\begin{document}
\begin{table}\caption{Correlation or something}
\centering
\pgfplotstabletypeset[color cells]{
x,a,b,c,d
a,90,,,
b,0,80,,
c,0,0,-95,
d,0,10,5,-85
}
\end{table}
\end{document}
结果和上面一样。