我试过了,但似乎不起作用
\addplot +[raw gnuplot, thick, red, mark=none, smooth] to mark=x,mark options={draw=blue}
平均能量损失
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots, pgfplotstable}
\pgfplotsset{compat=newest}
\usepackage{filecontents}
\begin{filecontents*}{data.dat}
X Y
2007 19348
2008 23457
2009 32624
2010 34270
2011 46888
2012 45224
2013 53556
2014 55007
2015 49664
\end{filecontents*}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
legend pos=outer north east,
xticklabel style={/pgf/number format/1000 sep={}},
legend cell align=left
]
\addplot [only marks, mark = *] table {data.dat};
\addlegendentry{Data}
\addplot +[raw gnuplot, thick, red, mark=none, smooth] gnuplot {
FIT_LIMIT=1.e-14;
f(x)=a*x+b;
fit f(x) 'data.dat' using 1:2 via a,b;
% Next, plot the function using the x positions from the table
plot 'data.dat' using 1:(f($1))
set print "parameters.dat"; % Open a file to save the parameters into$
print a,b;
};
\addlegendentry[]{\pgfplotstableread{parameters.dat}\parameters% Open the file Gnuplot wrote
\pgfplotstablegetelem{0}{0}\of\parameters \edef\paramA{\pgfplotsretval}% Get first element, save into \paramA
\pgfplotstablegetelem{0}{1}\of\parameters \edef\paramB{\pgfplotsretval}% Get second element, save into \paramB
$\pgfmathprintnumber{\paramA} x \pgfmathprintnumber{\paramB}$
}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
不是一个完整的解决方案:我无法正确使用\pgfplotsinvokeforeach
。我删除了 gnuplot 部分,仅使用 pgf 功能。
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots, pgfplotstable}
\usetikzlibrary{arrows}
\pgfplotsset{compat=newest}
\begin{filecontents*}{data.dat}
X Y
2007 19348
2008 23457
2009 32624
2010 34270
2011 46888
2012 45224
2013 53556
2014 55007
2015 49664
\end{filecontents*}
\pgfplotstableread{data.dat}\tabledata
\pgfplotstablegetrowsof{\tabledata}
\pgfmathsetmacro\numberofrows{\pgfplotsretval-1}
\begin{document}
\begin{tikzpicture}[>=latex',]
\begin{axis}[
legend pos=outer north east,
xticklabel style={/pgf/number format/1000 sep={}},
legend cell align=left
]
\addplot [only marks, mark = *] table {\tabledata};
\addlegendentry{Data}
\addplot table [mark=none,
x=X,
y={create col/linear regression={y=Y}}]
{\tabledata};
\addlegendentry{%
$\pgfmathprintnumber{\pgfplotstableregressiona} \cdot x
\pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$}
\pgfplotsinvokeforeach{0,...,\numberofrows}{% draw only the last one…
\pgfkeys{/pgf/fpu} % because of "too large dimension" error
\pgfplotstablegetelem{#1}{X}\of\tabledata
\pgfmathsetmacro\x{\pgfplotsretval}
\pgfplotstablegetelem{#1}{Y}\of\tabledata
\pgfmathsetmacro\y{\pgfplotsretval}
\pgfmathsetmacro\z{\pgfplotstableregressiona*\x+\pgfplotstableregressionb}%
\pgfkeys{/pgf/fpu=false}
\draw [->] (axis cs:\x, \y) -- (axis cs:\x, \z);%
}
\end{axis}
\end{tikzpicture}
\end{document}