Home > Software engineering >  Using julia's PyPlot shows the address of the image instead of the image
Using julia's PyPlot shows the address of the image instead of the image

Time:05-09

I wrote a least squares method in Julia, and the following information is prompted when I want to draw a graph.(In jupyter in Vscode and includes the julia extension.)

PyObject <matplotlib.collections.PathCollection object at 0x00000000017978E0>

I have added the show() command, but it doesn't output the picture either, giving the following prompt.

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

All codes are as follows.

using PyPlot
function leastsqfit(x::Array,y::Array,n)
    m=length(x)
    d=n 1
    A,b=zeros(d,d),zeros(d,1)
    p=Array{Float64}(undef,2*n 1)
    for k in 1:d
        sum=0
        for i in 1:m
            sum=sum y[i]*x[i]^(k-1)
        end
        b[k]=sum
    end
    p[1]=m
    for i in 2:2*n 1
        sum =0
        for j in 1:m
            sum=sum x[j]^(i-1)
        end
        p[i]=sum
    end
    for k in 1:d
        for j in k:d
            A[k,j]=p[k j-1]
        end
    end
    for i in 2:d
        for j in 1:i-1
            A[i,j]=A[j,i]
        end
    end
    a=A\b
end
function poly(x,A::Array)
    d,sum=length(A),0
    for i in 1:d
        sum=sum A[i]*x^(i-1)
    end
    return sum
end
function SSE(A::Array,x::Array,y::Array)
    m,sum=length(y),0
    for i in 1:m
        sum=sum (y[i]-poly(x[i],a))^2
    end
    return sum
end
function Pollt(x::Array,y::Array,n)
    n=length(x)
    a=leastsqfit(xd,yd,1)
    xaxis=x[1]:1/100:x[n]
    yvals=map(x->poly(x,a),xaxis)
    plot(xaxis,yvals)
    scatter(x,y)
end
xd=[1,2,3,4,5,6]
yd=[3,5,9.2,11,14.5,19]
a=leastsqfit(xd,yd,1)
display(a)
Pollt(xd,yd,1)
#show()

I'm a beginner in julia language, I don't know anything about the above problems, I hope you can help me.

CodePudding user response:

to capture the figure you can add

gcf() at the end of Pollit this way the returned value will be the current figure and Jupyter will show it.

function Pollt(x::Array,y::Array,n)
    n=length(x)
    a=leastsqfit(xd,yd,1)
    xaxis=x[1]:1/100:x[n]
    yvals=map(x->poly(x,a),xaxis)
    plot(xaxis,yvals)
    scatter(x,y)
    gcf()
end

Otherwise also calling f = gcf() after colling Pollit will make f be the figure and Jupyter shouls show it when it is the last element of a cell or also calling display(f) at some point in the cell.

So also something like

function Pollt(x::Array,y::Array,n)
    n=length(x)
    a=leastsqfit(xd,yd,1)
    xaxis=x[1]:1/100:x[n]
    yvals=map(x->poly(x,a),xaxis)
    plot(xaxis,yvals)
    scatter(x,y)
    f = gcf()
    display(f)
    more_code...
end

Should work.

  • Related