我有两个散点图来自一个 csv 文件。
no,id,x,y,x_proj,y_proj
1,1,565,417,565.6,393.3
1,2,315,234,334.8,193
1,3,949,355,944.8,346.3
我想链接每个具有相同 ID 的点。有没有简单的方法可以做到这一点?
我目前拥有的代码:
\documentclass{article}
\usepackage{filecontents}
\usepackage{pgfplots}
\begin{document}
\begin{filecontents*}{data.csv}
no,id,x,y,x_proj,y_proj
1,1,565,417,565.6,393.3
1,2,315,234,334.8,193
1,3,949,355,944.8,346.3
\end{filecontents*}
\begin{tikzpicture}
\begin{axis}[
enlargelimits=false,
xmin=0, xmax=1280,
ymin=0, ymax=720,
]
\addplot[
only marks,
scatter,
mark=*,
mark size=2pt]
table[meta index=1, col sep=comma, x=x,y=y]{data.csv};
\addplot[
only marks,
scatter,
mark=*,
mark size=2pt]
table[meta index=1, col sep=comma, x=x_proj,y=y_proj]{data.csv};
\end{axis}
\end{tikzpicture}
\end{document}
提前致谢,
答案1
这可以通过为每个点添加一个坐标来实现。然后您只需连接相应的坐标即可。
有关详细信息,请查看代码中的注释。
(代码根据https://tex.stackexchange.com/a/335625)
% used PGFPlots v1.15
\begin{filecontents*}{data.csv}
no,id,x,y,x_proj,y_proj
1,1,565,417,565.6,393.3
1,2,315,234,334.8,193
1,3,949,355,944.8,346.3
\end{filecontents*}
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\pgfplotstableread[col sep=comma]{data.csv}{\loadedtable}
% store number of data points
\pgfplotstablegetrowsof{\loadedtable}
\pgfmathtruncatemacro{\N}{\pgfplotsretval-1}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
% % (commented to enlarge the distance between the points)
% enlargelimits=false,
% xmin=0, xmax=1280,
% ymin=0, ymax=720,
]
\addplot[
only marks,
scatter,
mark=*,
% % -------------------------------------------------------------
% % comment this block to hide names of the coords
% % -----
% % just for debugging purposes you can draw the names of the
% % coordinates to check that everything is right/fine
% nodes near coords=a\coordindex,
% % increase the distance of the nodes a bit
% nodes near coords align={above=1ex},
% % -------------------------------------------------------------
] table [x=x,y=y,meta index=1] {\loadedtable}
% set a coordinate on each data point
\foreach \i in {0,...,\N} {
coordinate [pos=\i/\N] (a\i)
}
;
\addplot[
only marks,
scatter,
mark=*,
% % -------------------------------------------------------------
% nodes near coords=b\coordindex,
% nodes near coords align={below=1ex},
% % -------------------------------------------------------------
] table [x=x_proj,y=y_proj,meta index=1] {\loadedtable}
% set a coordinate on each data point
\foreach \i in {0,...,\N} {
coordinate [pos=\i/\N] (b\i)
}
;
\end{axis}
% now draw the connecting lines
\foreach \i in {0,...,\N} {
\draw (a\i) -- (b\i);
}
\end{tikzpicture}
\end{document}