我正在使用y = {create col/linear regression={y=data}}
来根据addplot
从文件中提取的数据生成最佳拟合线。如何强制该线包含原点作为其必须通过?
梅威瑟:
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}[H]
\begin{tikzpicture}
\begin{axis}
\addplot table [
x = data1,
y = {create col/linear regression = {y = data2}}
] {data_file.txt};
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}
答案1
我用的是Jake 的随机情节示例作为提出划定此条线的可能方法的基础。我无法判断这是否就是你心中的“那条”线。
\documentclass[fleqn]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.16}
% from https://tex.stackexchange.com/a/445369/121799
\newcommand*{\ReadOutElement}[4]{%
\pgfplotstablegetelem{#2}{#3}\of{#1}%
\let#4\pgfplotsretval
}
\begin{document}
\pgfmathsetseed{1138} % set the random seed
\pgfplotstableset{ % Define the equations for x and y
create on use/x/.style={create col/expr={2*\pgfplotstablerow}},
create on use/y/.style={create col/expr={2*(2*rand)^2+3*rand}}
}
% create a new table with 30 rows and columns x and y:
\pgfplotstablenew[columns={x,y}]{30}\loadedtable
\section*{``Theory''}
As I said in my comments, I do not know what you want to achieve. So I made an
assumption. Clearly, the only free parameter of a line running through the
origin is its slope, $a$. That is, the line is given by
\[ y(x)~=~a\,x\;.\]
Call the data points $\{(x_i,y_i)_{1\le i\le n}\}$. One way to fix the line is
that the sum of all distances to the line vanishes, i.e.
\[ \sum\limits_{i=1}^n\left(a\,x_i-y_i\right)~=~0\;.\]
This implies that
\[ a~=~\frac{\sum\limits_{i=1}^ny_i}{\sum\limits_{i=1}^nx_i}\;,\]
which is what is used below.
\section*{Example}
\pgfplotstablegetrowsof{\loadedtable}
\pgfmathtruncatemacro{\rownum}{\pgfplotsretval-1}
\pgfmathsetmacro{\sumx}{0}
\pgfmathsetmacro{\sumy}{0}
\pgfmathsetmacro{\xmax}{0}
\foreach \X in {0,...,\rownum}
{\ReadOutElement{\loadedtable}{\X}{x}{\tmpx}
\ReadOutElement{\loadedtable}{\X}{y}{\tmpy}
\pgfmathsetmacro{\sumx}{\sumx+\tmpx}
\xdef\sumx{\sumx}
\pgfmathsetmacro{\sumy}{\sumy+\tmpy}
\xdef\sumy{\sumy}
\pgfmathsetmacro{\xmax}{max(\xmax,\tmpx)}
\xdef\xmax{\xmax}}
\pgfmathsetmacro{\myslope}{\sumy/\sumx}
\begin{tikzpicture}
\begin{axis}[
xlabel=$x$, % label x axis
ylabel=$y$, % label y axis
axis lines=middle, %set the position of the axes
clip=false
]
\addplot [only marks] table {\loadedtable};
%\addplot [no markers, thick, red] table [y={create col/linear regression={y=y}}] {\loadedtable} node [anchor=west] {$\pgfmathprintnumber[precision=2, fixed zerofill]{\pgfplotstableregressiona} \cdot \mathrm{Weight} + \pgfmathprintnumber[precision=1]{\pgfplotstableregressionb}$};
\addplot [no markers, thick, red,domain=0:\xmax] {\myslope*x};
\end{axis}
\end{tikzpicture}
\end{document}
如果您有另一种方法来固定斜率,修改此代码可能会提供一种实现您想要的方法。