Reputation: 209
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?
Upvotes: 4
Views: 1190
Reputation: 6086
Interestingly, since Plots handles an array of Tuples as an array of (x, y) points, this works:
plot(Tuple.(M))
Upvotes: 1
Reputation: 14735
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.
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.
Upvotes: 5