![使键成为全局键或在范围之外引用它们](https://linux22.com/image/474420/%E4%BD%BF%E9%94%AE%E6%88%90%E4%B8%BA%E5%85%A8%E5%B1%80%E9%94%AE%E6%88%96%E5%9C%A8%E8%8C%83%E5%9B%B4%E4%B9%8B%E5%A4%96%E5%BC%95%E7%94%A8%E5%AE%83%E4%BB%AC.png)
我制作了此代码作为此处的答案:向 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"}
— 或者当范围关闭时它会丢失吗?
如果width
和height
没有被赋予axis
,它们就不会被存储在键中。它们还能被引用吗?
使密钥全局化的最佳方法是什么?
在代码中,我使用
\pgfmathparse{\pgfkeysvalueof{/pgfplots/width}} \global\let\savedwidth\pgfmathresult
但这似乎有些倒退。