# How do I plot?

xfirst=rand(-5:5)

for n=1:100

``````a=rand(-0.1:0.1)

xnew=xfirst+(xfirst*a)

if mainfonk(xnew)>mainfonk(xfirst)

xfirst=xnew

println(mainfonk(xfirst))

end
``````

end

Hi. I am working hill climbing in julia. I am trying to find how can I create graph this code. But I didnt find. I want to create a graph by printing the resulting S values on the y axis and the number of iterations it finds on the x axis.Can you help me?

Hi there! The word used is likely â€śplotâ€ť rather than â€śgraphâ€ť. So if you search your tutorials or manuals for â€śplotâ€ť you should find some clues. Thereâ€™s a JuliaPlots organzsation, which should be a good place to start learning.

Besides the plotting, there are some issues with your code. For example, `rand(-0.1:0.1)` always gives you the same result, and `xnew=xfirst+(xfirst*a)` never makes progress when `xfirst` is zero.

You could rewrite it like this (requires Plots and Distributions package):

``````import Distributions: Uniform

# one iteration
function step(xfirst,mainfct)
a=rand(Uniform(-0.1,0.1))
xnew=xfirst+a
if mainfct(xnew)>mainfct(xfirst)
return xnew
end
return xfirst
end

function runSteps(xfirst,mainfct,n=100)
xarr = [xfirst]
for i=1:n
xfirst = step(xfirst,mainfct)
push!(xarr, xfirst)
end
return xarr
end

mainfct(x) = (x+1.0)^2 # your input function

xfirst = 0.0 # starting value
xarr = runSteps(xfirst, mainfct, 100) # run 100 steps
yarr = mainfct.(xarr) # get function values

using Plots
plot(0:length(yarr)-1, yarr, xlabel="iterations", ylabel="function value at iteration",label="")
``````
1 Like

There are a number of actively maintained packages around for plotting. They differ in the kind of interface they provide, the features etc. I believe the most widely used ones right now are probably Gadfly.jl, Makie.jl, PlotlyJS.jl, Plots.jl and VegaLite.jl (in alphabetical order). I might well have missed some