使键成为全局键或在范围之外引用它们

使键成为全局键或在范围之外引用它们

我制作了此代码作为此处的答案:向 pgfplots 添加第二(x)轴的有效“宏”以及更普遍的情况。

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\pgfplotsset{
mainaxis/.style={
tick pos=bottom,
before end axis/.code={
  \pgfmathparse{\pgfkeysvalueof{/pgfplots/width}} \global\let\savedwidth\pgfmathresult
  \pgfmathparse{\pgfkeysvalueof{/pgfplots/height}} \global\let\savedheight\pgfmathresult
  \pgfmathparse{\pgfkeysvalueof{/pgfplots/xmin}} \global\let\savedxmin\pgfmathresult
  \pgfmathparse{\pgfkeysvalueof{/pgfplots/xmax}} \global\let\savedxmax\pgfmathresult
  \pgfmathparse{\pgfkeysvalueof{/pgfplots/ymin}} \global\let\savedymin\pgfmathresult
  \pgfmathparse{\pgfkeysvalueof{/pgfplots/ymax}} \global\let\savedymax\pgfmathresult
}}}
\newenvironment{secondxaxis}[1][]{\begin{axis}[width=\savedwidth, height=\savedheight, axis line style={draw=none}, xtick pos=top, ytick=\empty, ymin=\savedymin, ymax=\savedymax, #1]}{\end{axis}}
\newenvironment{secondyaxis}[1][]{\begin{axis}[width=\savedwidth, height=\savedheight, axis line style={draw=none}, ytick pos=right, xtick=\empty, xmin=\savedxmin, xmax=\savedxmax, #1]}{\end{axis}}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
name=main,
mainaxis,
width=10cm, height=5cm,
xmin=10, xmax=20,
ymin=30, ymax=40,
xlabel=main x, ylabel=main y,
%axis line style={draw=none}, xtick=\empty, ytick=\empty, %uncomment to see only second axis
]
\addplot[red, only marks] coordinates {(12,32)};
\end{axis}
\begin{secondxaxis}[
xmin=1, xmax=2,
xlabel=second x,
]
\addplot[green, only marks] coordinates {(1.5,34)};
\end{secondxaxis}
\begin{secondyaxis}[
ymin=3, ymax=4,
ylabel=second y,
]
\addplot[blue, only marks] coordinates {(18,3.6)};
\end{secondyaxis}
\end{tikzpicture}
\end{document}

四边都有轴且有三个点的图形

如何最好地重用范围外的密钥?它是否需要是全局的,还是可以通过其他方式引用?例如

\pgfkeysvalueof{/pgfplots/"name of scope"/"key in that scope"}

— 或者当范围关闭时它会丢失吗?

如果widthheight没有被赋予axis,它们就不会被存储在键中。它们还能被引用吗?

使密钥全局化的最佳方法是什么?

在代码中,我使用

\pgfmathparse{\pgfkeysvalueof{/pgfplots/width}} \global\let\savedwidth\pgfmathresult

但这似乎有些倒退。

相关内容