I solved a linear bi-objective mixed integer problem and I want to plot the results. results include lines and points. for example
list=[([0.0; 583000.0], 0), ([190670.0; 149600.0], 0), ([69686.0, 385000.0], 1), ([33296.0, 484000.0], 1), ([136554.0, 2.38075e5], 1), ([24556.0, 503800.0], 0), ([47462.0, 437800.0], 1), ([129686.0, 253000.0], 1), ([164278.0, 178200.0], 1)]
In this list third point ([69686.0, 385000.0], 1)
second element 1
is determined that this point connected by a line to prior point ([190670.0; 149600.0], 0)
is connected to second point by a line.
I coded that as follow:
using JuMP,Plots
list=[([0.0, 583000.0], 0), ([24556.0, 503800.0], 0), ([33296.0, 484000.0],1), ([47462.0, 437800.0], 1), ([69686.0, 385000.0], 1), ([129686.0, 253000.0], 1), ([136554.0, 23805.0], 1), ([164278.0, 178200.0], 1), ([190670.0, 149600.0], 0)]
x=zeros(1,1)
for i=1:size(list,1)
x=[x;list[i][1][1]]
end
row=1
x = x[setdiff(1:end, row), :]
y=zeros(1,1)
for i=1:size(list,1)
y=[y;list[i][1][2]]
end
row=1
y = y[setdiff(1:end, row), :]
for i=2:size(list,1)
if list[i][2]==0
plot(Int(x[i]),Int(y[i]),seriestype=:scatter)
plot(Int(x[i+1]),Int(y[i+1]),seriestype=:scatter)
end
if list[i][2]==1
plot(Int(x[i]),Int(y[i]))
plot(Int(x[i+1]),Int(y[i+1]))
end
end
but it is not worked. would you please help me. thanks
You can simply push each line segment's x and y values to two separate arrays, x
and y
in the code below. After each line segment's values (i.e. x1 and x2 or y1 and y2) put a NaN
into the arrays. This will prevent connecting a line segment to the next one if there should not be a connection. (for example, the case you see 1 and then a 0). And finally plot(x, y)
.
The following code snippet does it. Note that allx
and ally
are used to hold all points regardless of connection status. You may want to exclude connected points from them. x
and y
holds connected line segments.
using Plots
x, y, allx, ally = Float64[], Float64[], Float64[], Float64[]
# iterate through list
for i = 1:length(list)-1
if list[i+1][2] == 1
# push x1 from the first point, x2 from the second and a `NaN`
push!(x, list[i][1][1], list[i+1][1][1], NaN)
# push y1, y2, `NaN`
push!(y, list[i][1][2], list[i+1][1][2], NaN)
end
push!(allx, list[i][1][1])
push!(ally, list[i][1][2])
end
push!(allx, list[end][1][1])
push!(ally, list[end][1][2])
# scatter all points
scatter(allx, ally)
# plot connections with markers
plot!(x, y, linewidth=2, color=:red, marker=:circle)
This should hopefully give you the plot you wanted.
If you happen to use Gadfly.jl
instead of Plots.jl
, you can get a similar plot with
using Gadfly
connectedpoints = layer(x=x, y=y, Geom.path, Geom.point, Theme(default_color="red"))
allpoints = layer(x=allx, y=ally, Geom.point)
plot(connectedpoints, allpoints)
As a side note if you plan to plot another series on top of a plot object already created, you should use plot!
instead of plot
.