pgfplots:轴标签的条件“内部分离”

pgfplots:轴标签的条件“内部分离”

如果是而非,我该如何将设置inner sep为?xlabel0ptemptyxlabel=<text>

我的意思是
\ifx\pgfkeysvalueof{/pgfplots/xlabel} \empty inner sep=0pt \else 5pt\fi

很多

\documentclass[a4paper]{article}
\usepackage{pgfplots}

\begin{document}
\pgfplotsset{
xlabel=\empty,  ylabel=\empty, % "default"
every axis x label/.append style={
%inner sep=0pt
},
}

\begin{tikzpicture}[
mystyle/.style={anchor=west, fill=yellow, minimum width=1cm}
]
\begin{axis}[
clip=false, 
ylabel={The y Label},
every axis label/.append style={draw}, 
]
\addplot coordinates {(0,-5) (1,1) (2,2)};

\node[mystyle] (xl) {xlabel: \pgfkeysvalueof{/pgfplots/xlabel}};
\node[mystyle, above of=xl] {ylabel: \pgfkeysvalueof{/pgfplots/ylabel}};
\end{axis}
\end{tikzpicture}
\end{document}

答案1

您可以使用类似这样的方法:

\pgfplotsset{
  every axis x label/.append code={%
    \protected@edef\zzz{\pgfkeysvalueof{/pgfplots/xlabel}}%
    \expandafter\ifblank\expandafter{\zzz}
      {\pgfkeysalso{inner sep=0pt}}
      {\pgfkeysalso{inner sep=5pt}}%
  },
}

这将测试 x 标签是否空白的(确切地说:扩展后为空或仅包含空格\protected@edef)。如果您确实希望空白但非空的 x 标签具有5pt与其他非空 x 标签一样的内部分隔符,只需使用 的etoolbox\ifstrempty而不是\ifblank。例如,可以使用 来看到它们之间的区别xlabel={\space}

由于\ifblank(以及\ifstrempty)是完全可扩展的,因此也可以这样写:

\pgfplotsset{
  every axis x label/.append code={%
    \protected@edef\zzz{\pgfkeysvalueof{/pgfplots/xlabel}}%
    \pgfkeysalso{inner sep/.expanded={%
      \expandafter\ifblank\expandafter{\zzz}{0}{5}pt}}%
  },
}

完整示例:

\documentclass{article}
\usepackage{etoolbox}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}

\makeatletter
\pgfplotsset{
  xlabel=\empty,  ylabel=\empty, % "default"
  every axis x label/.append code={%
  \protected@edef\zzz{\pgfkeysvalueof{/pgfplots/xlabel}}%
  \expandafter\ifblank\expandafter{\zzz}
    {\pgfkeysalso{inner sep=0pt}}
    {\pgfkeysalso{inner sep=5pt}}%
  },
}
\makeatother

\begin{document}

% First plot with blank x label
\begin{tikzpicture}[
  mystyle/.style={anchor=west, fill=yellow, minimum width=1cm}
  ]
\begin{axis}[
  clip=false,
  ylabel={The y Label},
  every axis label/.append style={draw},
  ]
\addplot coordinates {(0,-5) (1,1) (2,2)};

\node[mystyle] (xl) {xlabel: \pgfkeysvalueof{/pgfplots/xlabel}};
\node[mystyle, above of=xl] {ylabel: \pgfkeysvalueof{/pgfplots/ylabel}};
\end{axis}
\end{tikzpicture}

\bigskip
% Second plot with non-blank x label
\begin{tikzpicture}[
  mystyle/.style={anchor=west, fill=yellow, minimum width=1cm}
  ]
\begin{axis}[
  clip=false,
  xlabel={Non blank label},
  ylabel={The y Label},
  every axis label/.append style={draw},
  ]
\addplot coordinates {(0,-5) (1,1) (2,2)};

\node[mystyle] (xl) {xlabel: \pgfkeysvalueof{/pgfplots/xlabel}};
\node[mystyle, above of=xl] {ylabel: \pgfkeysvalueof{/pgfplots/ylabel}};
\end{axis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

相关内容