4

So let's say I define the following array in Julia:

M=[[1,1],[2,4],[3,9],[4,16],[5,25],[6,36],[7,49],[8,64],[9,81],[10,100],[11,121],[12,144]]

Clearly each element [x,y] follows the quadratic rule $y=x^2$ and so I expect to get a parabolic shape when I plot it by using the command plot(M).

But instead I'm getting something like this:

What am I doing wrong, and what should I do to get my desired result -- a parabolic shape?

jboy
  • 209
  • 1
  • 5

2 Answers2

5

From the docs for Plots.jl:

The plot function has several methods:
plot(y): treats the input as values for the y-axis and yields a unit-range as x-values.

i.e. when you pass a single argument to plot, the values in the argument get interpreted as y-axis values, with the x-axis being 1, 2, 3, ....
Here, because M is a vector of vectors, a line plot is created for each of the inner vectors. For example, [3, 9] results in a line plot from (1, 3) to (1, 9).

To plot the parabola, in this case, you can do:

plot(first.(M), last.(M))

which will extract each first element of the inner array to form the x-axis, and each second element for the y-axis.

Parabolic curve

Of course, it's better to just create them as separate vectors in the first place, if you don't require M to be a vector of vectors for some other reason.


In case M is changed into a Matrix instead (which is the recommended way to create 2D arrays in Julia), for eg.

julia> M
12×2 Matrix{Int64}:
  1    1
  2    4
  3    9
etc.

then you can plot it with

julia> @views plot(M[:, 1], M[:, 2])

M[:, 1] gets all values on the first column (the x-axis), M[:, 2] the same on the second column (y-axis), and the @views at the beginning avoids these being allocated a new memory area unnecessarily, instead being read and used directly from M itself.

Sundar R
  • 13,776
  • 6
  • 49
  • 76
  • thanks for this. The actual 2D array I'm trying to play has 1000+ elements, and are generated by a different step in my project. Your answer is much more useful than if I manually create separate vectors for them. At least I think so, then again, I'm new to this. Thanks again! – jboy Sep 15 '22 at 00:15
  • Makes sense. However, keep in mind that Julia has an actual `Matrix` type, and an array of arrays is not the same thing as a 2D array in Julia. If the code that's creating `M` is also yours, strongly consider changing it to create a `Matrix` instead. – Sundar R Sep 15 '22 at 00:25
1

Interestingly, since Plots handles an array of Tuples as an array of (x, y) points, this works:

plot(Tuple.(M))

enter image description here

Bill
  • 5,600
  • 15
  • 27