我正在使用pgfplots
绘制函数图形x^4 - 2 * x^2 + 2
。在我的代码中,我使用了 \addplot [black, mark = *] 坐标五次。我该如何减少代码量?
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}
\usepackage{fouriernc}
\begin{document}
\begin{tikzpicture}
\begin{axis}
[
axis lines = center,
xlabel=$x$,ylabel=$y$,
domain=-3.5:3.5,
ymin=-0.85,
ymax=11,
xmin=-3,
xmax=3.5,
samples=100,xtick distance=1,
ytick distance=2,unit vector ratio*=1 1 1,
width=11cm,
grid=major,
grid style={gray!30}
]
\addplot [black, thick] {(x^4 - 2 * x^2 + 2};
\addplot [black] coordinates {(-0.25, -0.25)} node{$O$} {};
\addplot[color=blue,dashed] coordinates {
(-1, 0)
(-1, 1)
(1,1 )
(1, 0)
};
\addplot[color=blue,dashed] coordinates {
(-2, 0)
(-2, 10)
(2, 10)
(2,0 )
};
\addplot [black, mark = *] coordinates {( 0, 2)} ;
\addplot [black, mark = *] coordinates {(-1, 1)} ;
\addplot [black, mark = *] coordinates {(1, 1)} ;
\addplot [black, mark = *] coordinates {(-2, 10)} ;
\addplot [black, mark = *] coordinates {(2, 10)} ;
\end{axis}
\end{tikzpicture}
\end{document}
答案1
正如 Rmano 指出的那样,一个\addplot
命令就足够了,即
\addplot [black, mark = *,only marks] coordinates {( 0, 2)(-1, 1)(1, 1)(-2, 10)(2, 10)} ;
另一个选择是使用samples at
键\addplot
,然后pgfplots
计算 y 值:
\addplot [black, mark=*,only marks,samples at={0,-1,1,-2,2}] {(x^4 - 2 * x^2 + 2};
如果你想进一步缩短代码,你可以先声明一个函数,例如
declare function={Y(\x)=\x^4 - 2 * \x^2 + 2;}
Y(x)
并在不同的 s 中使用\addplot
。您还可以使用 缩短绘制虚线的代码\pgfplotsinvokeforeach
。
完整代码,输出与图像中的相同:
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}
\usepackage{fouriernc}
\begin{document}
\begin{tikzpicture}
\begin{axis}
[
declare function={Y(\x)=\x^4 - 2 * \x^2 + 2;},
axis lines = center,
xlabel=$x$,ylabel=$y$,
domain=-3.5:3.5,
ymin=-0.85,
ymax=11,
xmin=-3,
xmax=3.5,
samples=100,xtick distance=1,
ytick distance=2,unit vector ratio*=1 1 1,
width=11cm,
grid=major,
grid style={gray!30}
]
\addplot [black, thick] {Y(x)};
\addplot [black, mark=*,only marks,samples at={0,-1,1,-2,2}] {Y(x)};
\node at (axis cs:-0.25, -0.25) {$O$} ;
\pgfplotsinvokeforeach{1,2}{
\draw [blue,dashed] (axis cs:-#1,0) |- (axis cs:#1,{Y(#1)}) -- (axis cs:#1,0);
}
\end{axis}
\end{tikzpicture}
\end{document}
答案2
嗯...quick'n'dirty--定义一个命令:
\newcommand\splat[1]{ \addplot [black, mark = *] coordinates{#1} }
进而
\splat{( 0, 2)} ;
\splat{(-1, 1)} ;
\splat{(1, 1)} ;
\splat {(-2, 10)} ;
\splat {(2, 10)} ;
(可能有数百万种变化……)
或者在这种情况下你可以使用only marks
关键字:
\addplot [black, mark = *, only marks ] coordinates { ( 0, 2)
(-1, 1)
(1, 1)
(-2, 10)
(2, 10)};