How can I add third point in plot?
I seems to work when you replace /2
by *0.5
-- for whatever reason.
% used PGFPlots v1.16
\documentclass[border=5pt]{standalone}
\usepackage{xparse}
\usepackage{pgfplots}
\usetikzlibrary{matrix}
\pgfplotsset{
point legend/.style={},
point 1/.style={anchor=south},
point 2/.style={anchor=south},
point 3/.style={anchor=south}, % <-- added
azetinaplot/.style={
width=10cm,
height=8cm,
axis lines=middle,
xlabel=$x$,
ylabel=$y$,
enlarge y limits,
clip=false,
},
}
\NewDocumentCommand{\derivative}{O{f} m m m m O{rel axis cs:1,1}}{
\tikzset{declare function={#1(\x)=#2;}}
%
\addplot [thick, red, latex-latex] {#1(x)}
node [anchor=west] {#3}
;
\addplot [black, mark=*] coordinates {
(#4,{#1(#4)})
(#5,{#1(#5)})
}
node [pos=0,/pgfplots/point 1] {$P_1$}
node [pos=1,/pgfplots/point 2] {$P_2$}
;
% we need another `\addplot' for the third point to avoid drawing a line
% also to point 2
\addplot [black, mark=*, forget plot] coordinates {
({0.5*(#5+#4)},{#1(0.5*(#5+#4))}) % <-- repaced `/2' by `*0.5'
}
node [pos=0.5,/pgfplots/point 3] {$P_3$} % <-- added
;
\pgfplotsextra{
\pgfmathsetmacro\first{#1(#4)}
\pgfmathsetmacro\second{#1(#5)}
\pgfmathsetmacro\xdiff{#5-#4}
\pgfmathsetmacro\ydiff{#1(#5)-#1(#4)}
%
\draw (axis cs:#4,\first) -| (axis cs:#5,\second);
\draw [|-|,yshift=-2ex] (axis cs:#4,\first)
-- node [inner sep=1pt,fill=white] {\pgfmathprintnumber{\xdiff}}
(axis cs:#5,\first);
\draw [|-|,xshift=+2ex] (axis cs:#5,\first)
-- node [inner sep=1pt,fill=white] {\pgfmathprintnumber{\ydiff}}
(axis cs:#5,\second);
%
\matrix at (#6) [matrix of math nodes,/pgfplots/point legend] {
P_1=(#4\,,\,\pgfmathparse{#1(#4)}\pgfmathprintnumber{\pgfmathresult})\\
P_2=(#5\,,\,\pgfmathparse{#1(#5)}\pgfmathprintnumber{\pgfmathresult})\\
};
}
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
azetinaplot,
domain=-20:370, samples=100,
xmin=-20, xmax=370,
point 1/.append style={anchor=south east},
point 2/.append style={anchor=east},
]
\derivative{sin(\x)}
{$f(x)=\sin(x)$}
{290}{340}
[axis cs:150,-1] % position for the legend
% above we used the default function name f
% here we use the first optional argument to give the function the name g instead
\derivative[g]{cos(\x)+2}
{$f(x)=\cos(x)$}
{200}{300}
[axis cs:170,2.5] % position for the legend
\end{axis}
\end{tikzpicture}
\end{document}