我正在尝试使用此处的代码自动执行最小/最大值: 如何使用 pgfplots 和 scatter 自动标记局部极值?
- 水平线出现在标签的高度而不是点上(在 MWE2 中)
- 这里(在 MWE3 中)引出了关于在 tikz 上查找最小值/最大值的数值问题,所以我想我可以回到 > 500pt 的概念。一个有趣的替代方案是只标记一最小值,即第一个。
我尝试引入带有 true false 开关的 \ifx\first\undefined 和 \newbool{first},但它不会影响标记。
仅第一个就已经很不错了,但如果我能选择它们就更好了。
\documentclass[preview=false,tikz=true]{standalone}
\usepackage{pgfplots}
\usepackage{etoolbox}
\newbool{isFirst}
\makeatletter
\pgfplotsset{
/tikz/max node/.style={
anchor=south,
},
/tikz/min node/.style={
anchor=north,
name=minimum
},
mark min/.style={
point meta rel=per plot,
visualization depends on={x \as \xvalue},
scatter/@pre marker code/.code={%
\ifx\pgfplotspointmeta\pgfplots@metamin
\ifbool{isFirst}{
%\boolfalse{isFirst} % this does not actually disable next labels
\def\markopts{}%
\coordinate (minimum);
\node [min node] {
\pgfmathprintnumber[fixed]{\xvalue},%
\pgfmathprintnumber[fixed]{\pgfplotspointmeta}
};
}
{
\def\markopts{mark=none}
}
\else
\def\markopts{mark=none}
\fi
\expandafter\scope\expandafter[\markopts,every node near coord/.style=green]
},%
scatter/@post marker code/.code={%
\endscope
},
scatter,
},
mark max/.style={
point meta rel=per plot,
visualization depends on={x \as \xvalue},
scatter/@pre marker code/.code={%
\ifx\pgfplotspointmeta\pgfplots@metamax
\def\markopts{}%
\coordinate (maximum);
\node [max node] {
\pgfmathprintnumber[fixed]{\xvalue},%
\pgfmathprintnumber[fixed]{\pgfplotspointmeta}
};
\else
\def\markopts{mark=none}
\fi
\expandafter\scope\expandafter[\markopts]
},%
scatter/@post marker code/.code={%
\endscope
},
scatter
}
}
\makeatother
\begin{document}
\booltrue{isFirst}
\begin{tikzpicture}
\begin{axis}[
domain=-100:100,
axis lines*=middle,after end axis/.code={
\draw [thick, dashed, gray] (maximum) --({axis cs:0,0}-|maximum);
}
]
\addplot +[mark max,samples=5000] plot {sin(x)};
\end{axis}
\end{tikzpicture}
\booltrue{isFirst}
\begin{tikzpicture}
\begin{axis}[
domain=-100:100,
axis lines*=middle
,after end axis/.code={
\draw [thin, loosely dashed, gray] (minimum) -- ({rel axis cs:0,0}|-minimum);
\draw [thin, loosely dashed, gray] (minimum) -- ({rel axis cs:1,0}|-minimum);
}
]
\addplot +[mark min,samples=5000] plot {sin(8*x)};
\end{axis}
\end{tikzpicture}
\booltrue{isFirst}
\begin{tikzpicture}
\begin{axis}[
domain=-100:100,
axis lines*=middle
]
\addplot +[mark min,samples=5000] plot {sin(50*x)};
\end{axis}
\end{tikzpicture}
\end{document}
``