我知道我可以借助intersections
tikz 库做到这一点。但是,主要要求是避免任何临时路径(\path[name path=t] (2,0) -- (2,\ymaxv);
)并以某种方式命名它们。在大型项目中,它会变得混乱。
以下是我的两次尝试,但不幸的是没有成功:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}
\begin{axis}[axis lines = center]
\def\ymaxv{\pgfkeysvalueof{/pgfplots/ymax}}
\addplot[blue, name path global=x] {x};
% this doesn't work
\draw[red] (2,0) -- (intersection of {2,0--2,\ymaxv} and x);
% neither this does
\draw[red, name intersections={of={2,0--2,\ymaxv} and x}] (2,0) -- (intersection-1);
\end{axis}
\end{tikzpicture}
\end{document}
第一个(我知道它已被弃用)看不到x
路径,但另一个不能使用2,0--2,\ymaxv
路径。
答案1
这里我给出了两种添加垂直线的方法。具体细节请查看代码中的注释。
% used PGFPlots v1.18.1
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
% use this `compat` level or higher so for TikZ commands axis coordinates
% are used by default
\pgfplotsset{compat=1.11}
\begin{document}
\begin{tikzpicture}[
/pgf/declare function={
% define your function
f(\x) = (\x)^2;
% (optionally defines some constants so you only have *one* place where
% you need to change it)
a = 3;
},
]
\begin{axis}[
no markers,
]
\addplot {f(x)};
% to have vertical lines to y = 0 simply use `ycomb`
% (and works for arbitrary `\addplot`s, i.e. also table data etc.)
\addplot+ [ycomb,samples at={2}] {f(x)};
% to have vertical lines to arbitrary y-values you can e.g. use TikZ commands
\draw [green] (a, {f(a)}) -- (a, 20);
\end{axis}
\end{tikzpicture}
\end{document}
答案2
使用tzplot
包裹:
\documentclass{standalone}
\usepackage{tzplot}
\begin{document}
\begin{tikzpicture}
\tzaxes(-5,-5)(5,5)
\tzticks*[black!40](-3pt:3pt){-4,-2,2,4}(-3pt:3pt){-4,-2,2,4}
\tzticks<-3pt,-3pt>{-4,-2,2,4}{-4,-2,2,4}
\def\Fx{\x}
\tzfn[blue,thick]\Fx[-5:5]
\tzvXpointat{Fx}{2}(X)
\tzprojx[red,solid,thick](X)
\end{tikzpicture}
\end{document}