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}

相關內容