pgfplots 和带有 semilogyaxis 的线性回归

pgfplots 和带有 semilogyaxis 的线性回归

我想在我的图中添加一条线性回归线。MWE 为:

\begin{document}

\pgfplotstableread{
Year  ICumCDP
2008  3.73E-07
2009  3.35E-07
2010  2.01E-07
2011  3.88E-07
2012  1.36E-06
}{\tableICumCDP}
\pgfplotstablecreatecol[linear regression={ymode=log}, x=Year, y=ICumCDP]{regression}{\tableICumCDP}
\xdef\slope{\pgfplotstableregressiona}     % save the slope parameter
\xdef\intercept{\pgfplotstableregressionb} % save the intercept parameter

\begin{tikzpicture}
  \begin{semilogyaxis}[
    /pgf/number format/.cd,
    use comma,
    1000 sep={},
    log basis y = 10,
    ylabel = {ICumCDP},
    ymin = 1E-8,
    ymax = 1E-4,
    yminorgrids = true,
    xlabel = {Year},
    xtick = {2008,2009,2010,2011,2012}
]
    \addplot [only marks, color=blue, x=Year, y=ICumCDP] table {\tableICumCDP};
    \addplot [no markers, color=red, domain=2008:2012] {exp(x*\slope + \intercept)};
  \end{semilogyaxis}
\end{tikzpicture}\\
\end{document}

打印的回归线不正确:

图片

我的代码是修改的如何在使用 semilogyaxis 时将线性回归拟合扩展到整个 x 轴范围

我问过同样的问题德国论坛,但到现在还没人能帮助我。

答案1

这似乎是由于数值不准确(年份的数字很大,y 的数字很小)造成的。如果您转换数据(您可以随时进行转换),回归就会起作用:

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots, pgfplotstable}

\begin{document}

\pgfplotstableread{
Year  ICumCDP
2008  3.73E-07
2009  3.35E-07
2010  2.01E-07
2011  3.88E-07
2012  1.36E-06
}{\tableICumCDP}
\pgfplotstableset{
    create on use/shifted year/.style={ % Make the row number available
            create col/expr=\thisrow{Year}-2008
        }
}
\pgfplotstablecreatecol[linear regression={ymode=log, x=shifted year}]{regression}{\tableICumCDP}

\xdef\slope{\pgfplotstableregressiona}     % save the slope parameter
\pgfmathsetmacro\intercept{\pgfplotstableregressionb-\slope*2008}

\begin{tikzpicture}
  \begin{semilogyaxis}[
    /pgf/number format/.cd,
    use comma,
    1000 sep={},
    log basis y = 10,
    ylabel = {ICumCDP},
    ymin = 1E-8,
    ymax = 1E-4,
    yminorgrids = true,
    xlabel = {Year},
    xtick = {2008,2009,2010,2011,2012}
]
    \addplot [only marks, color=blue, x=Year, y=ICumCDP] table {\tableICumCDP};
    \addplot [no markers, color=red, domain=2008:2012] {exp((x)*\slope + \intercept)};
  \end{semilogyaxis}
\end{tikzpicture}\\
\end{document}

相关内容