假设我有一个带有多个数据系列的 pgfplots 轴。现在我循环遍历它并计算每个系列的线性回归。如何将回归线的斜率存储到 pgfplots 表列中?这是一个(非工作)最小示例:
\documentclass{article}
\usepackage{pgfplots,pgfplotstable}
\pgfplotsset{
compat=1.13
}
\begin{document}
%% Dummy data
\pgfplotstableread{
x1 y1 x2 y2
1 1 1 2
2 2 2 4
3 3 3 6
4 4 4 8
}{\mytable}
\begin{tikzpicture}
\begin{axis}[width=\textwidth,height=8cm]
\pgfplotsinvokeforeach{1,2}{
\addplot+[only marks,] table[x=x#1,y=y#1] {\mytable};
\addplot+[smooth,no markers] table[x=x#1,y={create col/linear regression={y = y#1}}]
{\mytable};
\xdef\slope##1{\pgfplotstableregressiona}
}
\end{axis}
\end{tikzpicture}
%% calling \slope1 and \slope2 doesn't seem to be a good way to do this, since it should automatically work independently of how many slopes I calculate. However, it doesn't work anyway.
\pgfplotstableread{
Nr slope
1 \slope1
2 \slope2
}{\atable}
\pgfplotstableset{
columns/slope/.style={column name=Slope},
}
\pgfplotstabletypeset[
columns={Nr,slope},
columns/Nr/.style={column type=l,column name=Nr},
]{\atable}
\end{document}
输出:
顺便说一句,我不知道这个函数的##1
作用是什么。我只是偶然用了它,然后发现它可以编译(但它不会在表格中打印正确的斜率)。
答案1
一种选择是使用 来etoolbox
存储\csxdef
值并\csuse
检索它:
\documentclass{article}
\usepackage{pgfplots,pgfplotstable}
\usepackage{etoolbox}
\pgfplotsset{
compat=1.13
}
\begin{document}
%% Dummy data
\pgfplotstableread{
x1 y1 x2 y2
1 1 1 2
2 2 2 4
3 3 3 6
4 4 4 8
}{\mytable}
\begin{tikzpicture}
\begin{axis}[width=\textwidth,height=8cm]
\pgfplotsinvokeforeach{1,2}{
\addplot+[only marks,] table[x=x#1,y=y#1] {\mytable};
\addplot+[smooth,no markers] table[x=x#1,y={create col/linear regression={y = y#1}}]
{\mytable};
\csxdef{slope #1}{\pgfplotstableregressiona}
}
\end{axis}
\end{tikzpicture}
%% calling \slope1 and \slope2 doesn't seem to be a good way to do this, since it should automatically work independently of how many slopes I calculate. However, it doesn't work anyway.
\pgfplotstableread{
Nr slope
1 \csuse{slope 1}
2 \csuse{slope 2}
}{\atable}
\pgfplotstableset{
columns/slope/.style={column name=Slope},
}
\pgfplotstabletypeset[
columns={Nr,slope},
columns/Nr/.style={column type=l,column name=Nr},
]{\atable}
\end{document}