向 pgfplots 添加第二(x)轴的有效“宏”

向 pgfplots 添加第二(x)轴的有效“宏”

最近,我不得不大量依赖于在绘图中添加第二个 x 轴。我使用以下脚本(参见 MWE)执行此操作,但是,对我来说,这似乎非常低效,当我需要更改主绘图的参数(宽度、高度、位置)时,会有很多重复的工作。因此,有没有办法将其写成“宏”,即类似于以下内容:

\begin{axis} [
    name=plot_main,
    width=100mm,
    height=50mm,
    xlabel={$x$},
    xmin=0,
    xmax=10,
    ymin=-1,
    ymax=1,
    x2label={$T$},
    x2min=0,
    x2max=2.5,
    x2tick={0,1,2},
]   
    \addplot[color=red, domain=0:10, samples=100]{sin(360*(1/4)*x)};
\end{axis}

提前致谢!

梅威瑟:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}
    
\begin{tikzpicture}
    \node[draw] (node) {Example};
    \begin{axis} [
        name=plot_main,
        at={(node.north east)},
        anchor=north west,
        xshift=20mm,
        width=100mm,
        height=50mm,
        xlabel={$x$},
        xmin=0,
        xmax=10,
        ymin=-1,
        ymax=1
    ]   
        \addplot[color=red, domain=0:10, samples=100]{sin(360*(1/4)*x)};
    \end{axis}
    \begin{axis} [
        name=plot_second_axis,
        at={(node.north east)},
        anchor=north west,
        xshift=20mm,
        width=100mm,
        height=50mm,
        ymin=-1,
        ymax=1,  % The above all needs to be changed if the main plot changes
        xlabel={$T$},
        xmin=0,
        xmax=2.5,
        xtick={0,1,2},  % The below is all standard and never changes
        ytick=\empty,
        axis line style={draw=none},
        xtick style={draw=none},
        axis x line*=top,
    ] 
    \end{axis}
\end{tikzpicture}

\end{document}

输出:

添加轴

答案1

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\node[draw] (node) {Example};
\pgfplotsset{
width=100mm, height=50mm,
ymin=-1, ymax=1,
}
\begin{axis}[
name=plot_main, 
at={(node.north east)}, xshift=2cm, anchor=north west,
xlabel={$x$},
xmin=0, xmax=10,
xtick pos=bottom,
]   
\addplot[red, domain=0:10, samples=100, smooth]{sin(360*(1/4)*x)};
\end{axis}
\begin{axis}[
name=plot_second_axis,
at={(plot_main.south west)},
xlabel={$T$},
xmin=0, xmax=2.5,
xtick distance=1, minor x tick num=1, ytick=\empty,
axis line style={draw=none},
axis x line*=top,
] 
\end{axis}
\end{tikzpicture}
\end{document}

具有两个 x 轴的正弦波图

相关内容