Change point position in Julia

Viewed 56
using Plots
p_arr = Array{Plots.Plot{Plots.GRBackend}}(undef,10,10);
x=5;
y=10;
p_arr[1,1] =  scatter!([x],[y],markersize=5,legend=false,markercolor = :green, showaxis = 
false,size=(500,500));
p_arr[1,2] = scatter!([x],[y],markersize=5,legend=false,markercolor = :green, showaxis = 
false,size=(500,500));

this is a very simple code of storing a point plot into an array. I just want to know how to change the x and y coordination for this point by the object it is stored in ?. in other words, I want to set x and y values by the object itself. is there a better way to do this. I am new to julia and I do not know where to search

1 Answers

While I'm not quite sure what you'll need for your end use case, storing an array of Plots.jl Plots.Plots has a lot of overhead and will not make it at all easy to modify the underlying points.

One approach that could be dramatically simpler would be to work directly with an array of Points instead. For example, let us first define:

struct Point{T}
   x::T
   y::T
end

then you have a type which can represent just an x-y point by itself. You can make an array of them:

p_arr = Array{Point{Int64}}(undef, 10, 10) # uninitialized, Int64

or to make this a little more interesting, an array of random points:

julia> p_arr = Point.(rand(10,10), rand(10,10))
10×10 Matrix{Point{Float64}}:
 Point{Float64}(0.561232, 0.39038)    …  Point{Float64}(0.0564275, 0.851144)
 ⋮                                    ⋱
 Point{Float64}(0.804435, 0.0717767)     Point{Float64}(0.110489, 0.670536)

If you want to be able to plot these, then let's define some functions to let Plots.jl know how to plot our Point type:

using Plots
import Plots.scatter
scatter(p::Point, args...; kwargs...) = scatter([p.x], [p.y], args...; kwargs...)
scatter(p::AbstractArray{<:Point}, args...; kwargs...) = scatter(map(p->p.x, p), map(p->p.y, p), args...; kwargs...)
# You can do the same for `scatter!` if you want that version too

then you can write

scatter(p_arr, label="", framestyle=:box)

to obtain a plot that looks like:

scatter plot of points

(note that each column gets its own series in Plots.jl, hence the multiple colors; call vec on your matrix of Points first if you don't want that)

Now, say you want to move one of those points. Let's say the first one:

julia> p_arr[1,1] = Point(5.0, 10.0)
Point{Float64}(5.0, 10.0)

Then plotting again

scatter(p_arr, label="", framestyle=:box)

will yield scatter plot with one point moved

Related