Reputation: 21233
I have some simple code that computes one value at a time. I would like a plot that updates as the code runs. At each iteration I compute a new value for the y-axis called avesofar
. I would just like to plot another point at x-index i
with this new value.
using Plots
function hamming4(bits1::Integer, bits2::Integer)
return count_ones(bits1 ⊻ bits2)
end
function random_strings2(n, N)
mask = UInt128(1) << n - 1
return [rand(UInt128) & mask for i in 1:N]
end
function find_min(strings, n, N)
minsofar = n
for i in 1:N
for j in i+1:N
dist = hamming4(strings[i], strings[j])
if dist < minsofar
minsofar = dist
end
end
end
return minsofar
end
function ave_min(n, N)
ITER = 100
strings = random_strings2(n, N)
new_min = find_min(strings, n, N)
avesofar = new_min
# print("New min ", new_min, ". New ave ", avesofar, "\n")
total = avesofar
for i in 1:ITER-1
strings = random_strings2(n, N)
new_min = find_min(strings, n, N)
avesofar = avesofar*(i/(i+1)) + new_min/(i+1)
print("New min ", new_min, ". New ave ", avesofar, "\n")
end
return avesofar
end
N = 2^15
n = 99
print("Overall average ", ave_min(n, N), "\n")
Upvotes: 1
Views: 593
Reputation: 925
You can update a plot in Plots by appending !
to the function name. So plot(x, y)
will create an initial plot with your points, and plot!(xnew, ynew)
will update the last plot with a new point.
So for your case, just add plot!(i, avesofar)
inside the loop. As mentioned by @przemyslaw-szufel you would use scatter
/scatter!
if you don’t want to connect the points with a line.
Upvotes: 2
Reputation: 42214
Here is how you plot one point at a time:
using Plots
pyplot()
p = Plots.scatter(; lab="")
Plots.scatter!(p, [1], [2]; lab="point 1")
Plots.scatter!(p, [3], [4]; lab="point 2")
Plots.scatter!(p, [5], [6]; lab="point 3")
Upvotes: 2