I was using the PyPlot library in Julia for plotting, and the scatter function seems to have a "little" inconvenience, namely, that only accepts the coordinates as two arguments: one array for all x values, and another for all y values, i.e.
scatter(xxs,yys)
with x=[x1,x2,...]
, and y=[y1,y2,...]
.
If I have a set or a tuple with points of coordinates, like,
A=([x1,y1],[x2,y2],...)
using pyplot/matplotlib directly in Python solves the inconvenience in one liner, as atested here in StackOverflow:
plt.scatter(*zip(*li))
but it seems that zip on Julia works completely different. Until now, I have come with following solution, but it seems quite inelegant:
x=[]
y=[]
for j in selectos
append!(x,j[2])
append!(y,j[1])
end
scatter(x,y, marker="o",c="black")
Is there a more "functional" or one-liner (or two liner) approach?
As mentioned in the other answer, one can use the same approach in Julia, i.e., scatter(zip(A...)...)
, but this is very slow for larger vectors and should be avoided.
Another possibility is to use getindex.(A, i)
to get a vector of all i
th elements of the vectors in A
.
julia> A = [[i, 10i] for i=1:5]
5-element Array{Array{Int64,1},1}:
[1, 10]
[2, 20]
[3, 30]
[4, 40]
[5, 50]
julia> getindex.(A,1)
5-element Array{Int64,1}:
1
2
3
4
5
julia> getindex.(A,2)
5-element Array{Int64,1}:
10
20
30
40
50
I can think of three approaches:
using PyPlot
A = ([1,2],[3,4],[5,6],[7,8])
# approach 1
scatter(zip(A...)...)
# approach 2
B = hcat(A...)
@views scatter(B[1,:], B[2,:])
# approach 3
scatter([x[1] for x in A], [x[2] for x in A])
The first one is probably most functional style.
In the second one you get B
which is easier to work with if you need to analyze the data; n.b. @views
requires Julia 0.6, but it can be omitted.
The third is probably the simplest to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With