How can I reduce my code when I used \addplot [black, mark = *] coordinates many times?
As Rmano pointed out, one \addplot
command is enough, i.e.
\addplot [black, mark = *,only marks] coordinates {( 0, 2)(-1, 1)(1, 1)(-2, 10)(2, 10)} ;
Another option would be use the samples at
key for \addplot
, and let pgfplots
calculate the y-values:
\addplot [black, mark=*,only marks,samples at={0,-1,1,-2,2}] {(x^4 - 2 * x^2 + 2};
If you want to shorten the code more, you can first declare a function with e.g.
declare function={Y(\x)=\x^4 - 2 * \x^2 + 2;}
and use Y(x)
in the different \addplot
s. You can also make the code drawing the dashed lines shorter using \pgfplotsinvokeforeach
.
Complete code, the output is the same as in your image:
\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}
Hmmm... quick'n'dirty --- define a command:
\newcommand\splat[1]{ \addplot [black, mark = *] coordinates{#1} }
And then
\splat{( 0, 2)} ;
\splat{(-1, 1)} ;
\splat{(1, 1)} ;
\splat {(-2, 10)} ;
\splat {(2, 10)} ;
(millions of variations possible...)
Or in this case you can just use the only marks
keyword:
\addplot [black, mark = *, only marks ] coordinates { ( 0, 2)
(-1, 1)
(1, 1)
(-2, 10)
(2, 10)};