4
$\begingroup$

Say I have a list

a={{1},{1},{1,2},{1,2}}

and I would like to make a ListPlot out of it, such that the value(s) stored as the elements of the array a are plotted at positions x={x1,x2,x3,x4}, i.e., I would like to plot the points {{x1,1},{x2,1},{x3,1},{x3,2},{x4,1},{x4,2}}

At the moment I'm doing this with this incredibly ugly function:

ListPlot[Reverse /@ Flatten[Partition[#, 2] & /@ MapThread[Append[Riffle[#1, #2], #2] &, {a, x}], 1]]

It works, but I can't imagine this is the best way. But ListPlot doesn't seem to be able to handle data with different lengths.

What am I missing?

$\endgroup$
5
$\begingroup$

How about

MapThread[Thread[{#1, #2}] &, {x, a}] // Flatten[#, 1] &
(* {{x1, 1}, {x2, 1}, {x3, 1}, {x3, 2}, {x4, 1}, {x4, 2}} *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks, this is fairly straigthforward! $\endgroup$ – Daniel May 8 at 21:08
5
$\begingroup$

Using Splice that was newly introduced in version 12.1:

Splice@*Thread /@ Transpose[{x, a}]

(* {{x1, 1}, {x2, 1}, {x3, 1}, {x3, 2}, {x4, 1}, {x4, 2}} *)
| improve this answer | |
$\endgroup$
5
$\begingroup$
thread0 = Inner[Thread @* List, ##, Join] &;

thread0[x, a]
{{x1, 1}, {x2, 1}, {x3, 1}, {x3, 2}, {x4, 1}, {x4, 2}}
t = {1, 3, 5, 15};

ListLinePlot[thread0[t, a]]

enter image description here

You can also use:

thread1 = Catenate @* Map[Thread] @* Thread @* List;

thread1[x, a]
 {{x1, 1}, {x2, 1}, {x3, 1}, {x3, 2}, {x4, 1}, {x4, 2}}

and

thread2 = MapThread[Apply[Sequence] @* Thread @* List];

thread2[{x, a}]
 {{x1, 1}, {x2, 1}, {x3, 1}, {x3, 2}, {x4, 1}, {x4, 2}}
| improve this answer | |
$\endgroup$
3
$\begingroup$

A variation on other answers:

 MapThread[##&@@Thread[{##}]&,{x,a}]

{{x1, 1}, {x2, 1}, {x3, 1}, {x3, 2}, {x4, 1}, {x4, 2}}

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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