我编写了以下代码,它基本上绘制了二项分布作为其参数的函数。
\begin{tikzpicture}[scale=1.5]
\begin{axis}[
domain=0:1,
axis lines=left,
grid=both,
xlabel=$\theta$,
ylabel=$L(\theta)$
]
\addplot[smooth,thick,black]
{factorial(50)/(factorial(10)*factorial(40)) *x^10 *(1-x)^40};
\addplot[smooth,dashed,red]
{0.0699};
\end{axis}
\end{tikzpicture}
得到下图所示的结果。
如您所见,峰值在 0.2 处,此时函数的值略大于 0.13。0.0699 处的红色虚线仅代表该高度的一半。
我现在的问题是,我是否可以在 x 轴上确定虚线与函数相交的两个点(我将其标记为 theta)。如果手动执行,计算会非常困难,我希望能够以图形方式看到它。
答案1
像这样吗?
代码:
\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}[scale=1.5]
\begin{axis}[
domain=0:1,
axis lines=left,
grid=both,
clip=false,
xlabel=$\theta$,
ylabel=$L(\theta)$
]
\addplot[name path=curve,smooth,thick,black]
{factorial(50)/(factorial(10)*factorial(40)) *x^10 *(1-x)^40};
\addplot[name path=line,smooth,dashed,red]
{0.0699};
\path[name intersections={of=curve and line, by={a,b}}];
\draw[dashed]
(a) -- (a|-{axis cs:0,0}) node[anchor=north,font=\tiny] {$\theta_1$};
\draw[dashed]
(b) -- (b|-{axis cs:0,0}) node[anchor=north,font=\tiny] {$\theta_2$};
\node[fill,inner sep=1.5pt] at (a) {};
\node[fill,inner sep=1.5pt] at (b) {};
\end{axis}
\end{tikzpicture}
\end{document}
这个想法是使用intersections
库并name path
(嗯......)命名路径;然后您可以让 TikZ 计算交叉点;使用name intersections
您可以为它们分配名称以进行进一步的操作。
要获取交点的坐标,您可以应用Jake's answer
到交叉口坐标:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\usetikzlibrary{intersections}
\begin{document}
\makeatletter
\newcommand\transformxdimension[1]{
\pgfmathparse{((#1/\pgfplots@x@veclength)+\pgfplots@data@scale@trafo@SHIFT@x)/10^\pgfplots@data@scale@trafo@EXPONENT@x}
}
\newcommand\transformydimension[1]{
\pgfmathparse{((#1/\pgfplots@y@veclength)+\pgfplots@data@scale@trafo@SHIFT@y)/10^\pgfplots@data@scale@trafo@EXPONENT@y}
}
\makeatother
\begin{tikzpicture}[scale=1.5]
\begin{axis}[
yticklabel style={/pgf/number format/.cd, fixed, fixed zerofill},
domain=0:1,
axis lines=left,
grid=both,
clip=false,
xlabel=$\theta$,
ylabel=$L(\theta)$
]
\addplot[name path global=curve,smooth,thick,black]
{factorial(50)/(factorial(10)*factorial(40)) *x^10 *(1-x)^40};
\addplot[name path global=line,smooth,dashed,red]
{0.0699};
\path[name intersections={of=curve and line, by={a,b}}];
\node[anchor=south] at (a)
{
\pgfgetlastxy{\macrox}{\macroy}
\transformxdimension{\macrox}
\pgfmathprintnumber{\pgfmathresult},%
\transformydimension{\macroy}%
\pgfmathprintnumber{\pgfmathresult}
};
\node[anchor=north west] at (b)
{
\pgfgetlastxy{\macrox}{\macroy}
\transformxdimension{\macrox}
\pgfmathprintnumber{\pgfmathresult},%
\transformydimension{\macroy}%
\pgfmathprintnumber{\pgfmathresult}
};
\draw[dashed]
(a) -- (a|-{axis cs:0,0}) node[anchor=north,font=\tiny] {$\theta_1$};
\draw[dashed]
(b) -- (b|-{axis cs:0,0}) node[anchor=north,font=\tiny] {$\theta_2$};
\node[fill,inner sep=1.5pt] at (a) {};
\node[fill,inner sep=1.5pt] at (b) {};
\end{axis}
\end{tikzpicture}
\end{document}