1
$\begingroup$

I like to do the following. I have a set of points that I plot in a ListPlot. I want overlay another plot where I connect the points with a line in a specific order ( Let's say connect point 1 with 5, 5 with 2 ...)

In the following there is a toy example of how my data look like:

identifier = Table[i, {i, 1, 10}];
cordx = RandomReal[10, 10];
cordy = RandomReal[10, 10];
data = Transpose@{identifier, cordx, cordy};

ListPlot[data[[All, 2 ;; 3]]]
$\endgroup$
3
  • $\begingroup$ cannot you just Show it together the set of lines you want to plot? $\endgroup$ Mar 1, 2016 at 14:51
  • 1
    $\begingroup$ you can specify the points to connect as a sequence, eg. ListLinePlot[data[[{1, 5, 2}, 2 ;; 3]]] to connect point 1 with 5, 5 with 2. $\endgroup$ Mar 1, 2016 at 14:53
  • $\begingroup$ Closely related Q/A: How to draw lines between specified dots on ListPlot? $\endgroup$
    – kglr
    Mar 2, 2016 at 7:04

2 Answers 2

5
$\begingroup$

Define the list of points you want to connect, here from 1->5, 3->5, 7->3, and 8->7 for example,

pointslist = {{1, 5}, {5, 2}, {7, 3}, {8, 7}};

Show[
 ListPlot[data[[All, 2 ;; 3]]],
 Graphics@(Line[{data[[#1, 2 ;; 3]], data[[#2, 2 ;; 3]]}] & @@@ 
    pointslist)]

enter image description here

Or, just a hair shorter,

ListPlot[data[[All, 2 ;; 3]], 
 Epilog -> (Line[{data[[#1, 2 ;; 3]], data[[#2, 2 ;; 3]]}] &) @@@ 
   pointslist]

gives the same output.

$\endgroup$
3
  • 2
    $\begingroup$ Epilog -> (Line[{data[[#1, 2 ;; 3]], data[[#2, 2 ;; 3]]}] &) @@@ pointslist also does the trick! (inside ListPlot) $\endgroup$
    – Aisamu
    Mar 1, 2016 at 15:07
  • $\begingroup$ @Aisamu, nice, that beats me by 6 bytes $\endgroup$
    – Jason B.
    Mar 2, 2016 at 9:41
  • $\begingroup$ Or, as I'd write to management, "nearly 10% increase in space-efficiency"! $\endgroup$
    – Aisamu
    Mar 2, 2016 at 13:44
2
$\begingroup$

If all points are to be connected in a specified order, the following also works.

lst = {1, 5, 2, 7, 3, 8, 4, 9, 6, 10};
Show[ListPlot[data[[All, 2 ;; 3]]], 
    ListLinePlot[Table[data[[i]], {i, lst}][[All, 2 ;; 3]]]]

enter image description here

$\endgroup$
1
  • 1
    $\begingroup$ This is definitely the way to go if the points are all connected in a path. I think you could shorten it by replacing the Show[.....] with ListLinePlot[data[[lst, 2 ;; 3]], PlotMarkers -> Automatic] $\endgroup$
    – Jason B.
    Mar 2, 2016 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.