我一直在尝试显示点和线之间的 y 差异。此代码
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}
\usetikzlibrary{calc}
\begin{document}
\begin{center}
\begin{tikzpicture}
\begin{axis}[title={title},xlabel={x},ylabel={y},xmajorgrids=true,ymajorgrids=true,scaled y ticks=false,y tick label style={/pgf/number format/fixed},ymin=355,xtick=data]
\addplot[mark=*,thick,black] coordinates{(1,433.6)(2,425.2)}
coordinate [pos=0] (start)
coordinate [pos=1] (end);
\coordinate (line) at (axis cs:1,365.2);
\draw[red,dashed] (line) -- (line -| end);
\draw[<->,dashed,shorten <=3pt]
let \p1=(line),
\p2=(end),
\n1={\y2-\y1} in
(end) -- node[anchor=east]{\pgfplotsconvertunittocoordinate{y}{\n1}\pgfplotscoordmath{y}{datascaletrafo inverse to fixed}{\pgfmathresult}\pgfmathprintnumber[fixed,precision=1]{\pgfmathresult}} (line -| end);
\end{axis}
\end{tikzpicture}
\end{center}
\end{document}
导致
并显示 415 而不是 60。这不是由于某种 LaTeX 数学不准确造成的,对吧?我的缩放操作是否出了问题?
答案1
我在手册中找不到你使用的命令,但一个相当标准的技巧是取未知距离和已知距离的比率来计算轴单位的距离。所以我将符号点之间的距离除以(例如)(axis cs:0,430)
和之间的已知距离,(axis cs:0,330)
然后知道轴单位的距离是多少。
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}
\usetikzlibrary{calc}
\begin{document}
\begin{center}
\begin{tikzpicture}
\begin{axis}[title={title},xlabel={x},ylabel={y},xmajorgrids=true,ymajorgrids=true,scaled y ticks=false,y tick label style={/pgf/number format/fixed},ymin=355,xtick=data]
\addplot[mark=*,thick,black] coordinates{(1,433.6)(2,425.2)}
coordinate [pos=0] (start)
coordinate [pos=1] (end);
\coordinate (line) at (axis cs:1,365.2);
\draw[red,dashed] (line) -- (line -| end);
\draw[<->,dashed,shorten <=3pt]
let \p1=(line),
\p2=(end),
\p3=($(axis cs:0,430)-(axis cs:0,330)$),
\n1={100*(\y2-\y1)/\y3} in
(end) -- node[anchor=east]{\pgfmathparse{\n1}%
\pgfmathprintnumber[fixed,precision=1]{\pgfmathresult}
} (line -| end);
\end{axis}
\end{tikzpicture}
\end{center}
\end{document}
答案2
现在看不出这怎么加起来,但似乎减法ymin
可以给出正确的值。即\pgfmathparse{\pgfmathresult-\pgfkeysvalueof{/pgfplots/ymin}}
在之前添加\pgfmathprintnumber
。
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.9}
\usetikzlibrary{calc}
\begin{document}
\begin{center}
\begin{tikzpicture}
\begin{axis}[title=title,xlabel={x},ylabel={y},xmajorgrids=true,ymajorgrids=true,scaled y ticks=false,y tick label style={/pgf/number format/fixed},ymin=355,xtick=data]
\addplot[mark=*,thick,black] coordinates{(1,433.6)(2,425.2)}
coordinate [pos=0] (start)
coordinate [pos=1] (end);
\coordinate (line) at (axis cs:1,365.2);
\draw[red,dashed] (line) -- (line -| end);
\draw[<->,dashed,shorten <=3pt]
let \p1=(line),
\p2=(end),
\n1={\y2-\y1} in
(end) -- node[anchor=east]{\pgfplotsconvertunittocoordinate{y}{\n1}\pgfplotscoordmath{y}{datascaletrafo inverse to fixed}{\pgfmathresult}\pgfmathparse{\pgfmathresult-\pgfkeysvalueof{/pgfplots/ymin}}\pgfmathprintnumber[fixed,precision=1]{\pgfmathresult}} (line -| end);
\end{axis}
\end{tikzpicture}
\end{center}
\end{document}