我想绘制一个范围为 [-2, 2] 的函数,但是 PGFplots 不断绘制更多内容:
为什么会出现这种情况?我该如何解决?
代码
\documentclass[varwidth=true, border=2pt]{standalone}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\usepackage{tikz}
\begin{document}
\pgfplotsset{
colormap={whitered}{
color(0.000cm)=(blue!50!black);
color(0.125cm)=(blue);
color(0.250cm)=(SkyBlue);
color(0.375cm)=(SkyBlue);
color(0.500cm)=(SpringGreen);
color(0.625cm)=(yellow);
color(0.750cm)=(yellow);
color(0.875cm)=(red);
color(1.000cm)=(red!50!black)
}
}
\begin{tikzpicture}
\begin{axis}[
domain=-2:2,
view={0}{90},
axis background/.style={fill=white},
]
\addplot3[surf,
samples=50,
shader=interp,
colormap name=whitered]
{x/exp(x^2+y^2)};
% \addplot3[contour gnuplot={number=15, labels=false},
% very thick,
% samples=30]
% {x/exp(x^2+y^2)};
\addplot3[blue,
quiver={
u={(1-2*x^2)*exp(-x^2-y^2)},
v={-2*x*y*exp(-x^2-y^2)},
scale arrows=0.3,
},
-stealth,samples=15]
{x/exp(x^2+y^2)};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
发生这种情况的原因是,计算轴范围时会考虑箭筒箭头的长度。从 (-2,0) 开始的箭头长度不为零,尖端略微偏左,因此轴范围会增加,以便可以看到完整的箭头。
要将轴范围限制在函数域内,请设置xmin=-2, xmax=2, ymin=-2, ymax=2
。
我还建议设置axis equal image
为沿 x 轴和 y 轴获得相同的缩放比例,并使用使用 pgfplots 绘制箭头图:使用 arrowsize 绘制箭头比例还可以缩放箭头尺寸,而不仅仅是长度:
\documentclass[varwidth=true, border=2pt]{standalone}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\usetikzlibrary{arrows.meta}
\begin{document}
\pgfplotsset{
colormap={whitered}{
color(0.000cm)=(blue!50!black);
color(0.125cm)=(blue);
color(0.250cm)=(SkyBlue);
color(0.375cm)=(SkyBlue);
color(0.500cm)=(SpringGreen);
color(0.625cm)=(yellow);
color(0.750cm)=(yellow);
color(0.875cm)=(red);
color(1.000cm)=(red!50!black)
}
}
\begin{tikzpicture}
\begin{axis}[
domain=-2:2,
view={0}{90},
axis background/.style={fill=white},
xmin=-2, xmax=2,
ymin=-2, ymax=2,
axis equal image,
point meta rel=per plot
]
\addplot3[surf,
samples=15,
shader=interp,
colormap name=whitered]
{x/exp(x^2+y^2)};
\addplot3[blue,
point meta={
sqrt(
((1-2*x^2)*exp(-x^2-y^2))^2+
(-2*x*y*exp(-x^2-y^2))^2
)
},
quiver={
u={(1-2*x^2)*exp(-x^2-y^2)},
v={-2*x*y*exp(-x^2-y^2)},
scale arrows=0.3,
every arrow/.append style={%
-{Latex[scale length={max(0.01,\pgfplotspointmetatransformed/1000)}]},
},
},
samples=15]
{x/exp(x^2+y^2)};
\end{axis}
\end{tikzpicture}
\end{document}