我正在尝试在 tikz 中制作一个包含多个图和一个网格的轴,其中一个图绘制在网格后面。具体来说,我想制作一个彩色区域来标记其他图的区域,但我希望网格位于其上方。但是,网格仍然应该位于其他图的后面。我不知道怎么做。我在 pgfplots 手册中读到,axis on top
可以用来移动全部在网格后面绘图,但这不是我需要的。
以下是 MWE:
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\definecolor{mycolor}{rgb}{0.8,1,0.8}%
\begin{tikzpicture}
\begin{axis}[%
width=8cm,
height=4cm,
xmajorgrids,
ymajorgrids,
% axis on top, % <-- uncomment to move all plots behind grid
]
% this should be behind the grid:
\addplot[fill=mycolor,draw=none,forget plot]
table[row sep=crcr]{
x y\\
0 -1 \\
1 -2 \\
1 1 \\
0 1 \\
};
% these should be in front of the grid
\addplot [color=black, line width=3pt]
table[row sep=crcr]{
0 0\\
.4 2\\
.6 1\\
1 1\\
};
\addplot [color=red, line width=3pt]
table[row sep=crcr]{
0 -1\\
.4 -2\\
.6 2\\
1 0\\
};
\end{axis}
\end{tikzpicture}%
\end{document}
以下是不理想的结果,其中绿色区域绘制在网格顶部:
答案1
pgfplots
有自己的图层集,因此您可以直接激活它set layers
,然后将on layer=axis background
其用作绿色背景;请参阅4.28.2 使用预定义图层和4.28.3 改变图形元素的层请参阅手册以了解更多信息:
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\definecolor{mycolor}{rgb}{0.8,1,0.8}%
\begin{tikzpicture}
\begin{axis}[%
width=8cm,
height=4cm,
xmajorgrids,
ymajorgrids,
set layers
]
% this should be behind the grid:
\addplot[fill=mycolor,draw=none,forget plot,on layer=axis background]
table[row sep=crcr]{
x y\\
0 -1 \\
1 -2 \\
1 1 \\
0 1 \\
};
% these should be in front of the grid
\addplot [color=black, line width=3pt]
table[row sep=crcr]{
0 0\\
.4 2\\
.6 1\\
1 1\\
};
\addplot [color=red, line width=3pt]
table[row sep=crcr]{
0 -1\\
.4 -2\\
.6 2\\
1 0\\
};
\end{axis}
\end{tikzpicture}%
\end{document}
答案2
最简单的方法是添加\usetikzlibrary{backgrounds}
然后
% this should be behind the grid:
\begin{scope}[on background layer]
\addplot[fill=mycolor,draw=none,forget plot]
table[row sep=crcr]{
x y\\
0 -1 \\
1 -2 \\
1 1 \\
0 1 \\
};
\end{scope}
代码:
\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{backgrounds}
\begin{document}
\definecolor{mycolor}{rgb}{0.8,1,0.8}%
\begin{tikzpicture}
\begin{axis}[%
width=8cm,
height=4cm,
xmajorgrids,
ymajorgrids,
% axis on top, % <-- uncomment to move all plots behind grid
]
% this should be behind the grid:
\begin{scope}[on background layer]
\addplot[fill=mycolor,draw=none,forget plot]
table[row sep=crcr]{
x y\\
0 -1 \\
1 -2 \\
1 1 \\
0 1 \\
};
\end{scope}
% these should be in front of the grid
\addplot [color=black, line width=3pt]
table[row sep=crcr]{
0 0\\
.4 2\\
.6 1\\
1 1\\
};
\addplot [color=red, line width=3pt]
table[row sep=crcr]{
0 -1\\
.4 -2\\
.6 2\\
1 0\\
};
\end{axis}
\end{tikzpicture}%
\end{document}