简体   繁体   中英

X ticks axis in matplotlib

Plot Figure

Hello Everyone, I am trying to plot a graph of contour but in very strange way the x values written in the x axis are not much to the real x values. I did not success solving that issue and wonder why this is happening. I tried changing the x ticks in many different ways but with no success, Hope someone can help me get out from this situation. Thanks!

`import numpy as np
import numdifftools as nd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def Function(x):
    return np.cos(x[0])+np.sin(x[1])+(1/5)*x[0]**2+(1/4)*x[1]**2

def hw10GDstep(f,x0):
    xold=x0[0]
    yold=x0[1]
    grad=nd.Gradient(Function)([xold,yold])
    Xnew=xold-0.2*grad[0]
    Ynew=yold-0.2*grad[1]
    X,Y=np.meshgrid(Xnew,Ynew)
    fval=f(X,Y)
    fval=list(fval)
    return ([Xnew,Ynew],fval[0][0])

def GradienDecent(f,x0):
    numberofiter=0
    xtol=10**-4
    norm=100
    xy=x0
    listofalliter=[]
    while(norm>xtol and numberofiter<1000):
        numberofiter=numberofiter+1
        step=hw10GDstep(f,xy)
        xy=step[0]
        fval=step[1]
        templist=[xy,fval,numberofiter]
        listofalliter.append(templist)
        grad=nd.Gradient(Function)([xy[0],xy[1]])
        norm=np.linalg.norm(grad)
    return (listofalliter)

f=lambda x,y:np.cos(x)+np.sin(y)+(1/5)*x**2+(1/4)*y**2
xlist=np.linspace(-10,10,1000)
ylist=np.linspace(-10,10,1000)
X,Y=np.meshgrid(xlist,ylist)
Z=f(X,Y)
plt.contourf(X,Y,Z,cmap ="bone")
x0_1=[7,7]
x0_2=[-7,-7]
x0_3=[0,-7]

x1=GradienDecent(f,x0_1)
x0_1listofx=[]
x0_1listofy=[]
for i in range(0,len(x1)):
    x0_1listofx.append(x1[i][0][0])
    x0_1listofy.append(x1[i][0][1])
x1iter=x1[len(x1)-1][2]
x1xmin=x1[len(x1)-1][0][0]
x1ymin=x1[len(x1)-1][0][1]
x1zmin=x1[len(x1)-1][1]
xyz1=[x1xmin,x1ymin,x1zmin]

x2=GradienDecent(f,x0_2)
x0_2listofx=[]
x0_2listofy=[]
for i in range(0,len(x2)):
    x0_2listofx.append(x2[i][0][0])
    x0_2listofy.append(x2[i][0][1])
x2iter=x2[len(x2)-1][2]
x2xmin=x2[len(x2)-1][0][0]
x2ymin=x2[len(x2)-1][0][1]
x2zmin=x2[len(x2)-1][1]
xyz2=[x2xmin,x2ymin,x2zmin]

x3=GradienDecent(f,x0_3)
x0_3listofx=[]
x0_3listofy=[]
for i in range(0,len(x3)):
    x0_3listofx.append(x3[i][0][0])
    x0_3listofy.append(x3[i][0][1])
x3iter=x3[len(x3)-1][2]
x3xmin=x3[len(x3)-1][0][0]
x3ymin=x3[len(x3)-1][0][1]
x3zmin=x3[len(x3)-1][1]
xyz3=[x3xmin,x3ymin,x3zmin]

print("For Start Point Of [7,7] Made: "+str(x1iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz1))
print("For Start Point Of [-7,-7] Made: "+str(x2iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz2))
print("For Start Point Of [0,-7] Made: "+str(x3iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz3))
print("The End.")
plt.plot_date(x0_1listofx,x0_1listofy,color='green',markersize=2,label="For Start Point Of [7,7]")
plt.plot_date(x0_2listofx,x0_2listofy,color='blue',markersize=2,label="For Start Point Of [-7,-7]")
plt.plot_date(x0_3listofx,x0_3listofy,color='red',markersize=2,label="For Start Point Of [0,-7]")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Gradient Descent For F(x,y):")
plt.colorbar()
plt.legend()
plt.show()

The plt.plot_date method is for plotting dates. Since your data is numerical, you can change plt.plot_date to plt.plot .

EDIT: to avoid connecting all of the data points together, pass marker='.' and linestyle='None' to the plt.plot method.

import numpy as np
import numdifftools as nd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def Function(x):
    return np.cos(x[0])+np.sin(x[1])+(1/5)*x[0]**2+(1/4)*x[1]**2

def hw10GDstep(f,x0):
    xold=x0[0]
    yold=x0[1]
    grad=nd.Gradient(Function)([xold,yold])
    Xnew=xold-0.2*grad[0]
    Ynew=yold-0.2*grad[1]
    X,Y=np.meshgrid(Xnew,Ynew)
    fval=f(X,Y)
    fval=list(fval)
    return ([Xnew,Ynew],fval[0][0])

def GradienDecent(f,x0):
    numberofiter=0
    xtol=10**-4
    norm=100
    xy=x0
    listofalliter=[]
    while(norm>xtol and numberofiter<1000):
        numberofiter=numberofiter+1
        step=hw10GDstep(f,xy)
        xy=step[0]
        fval=step[1]
        templist=[xy,fval,numberofiter]
        listofalliter.append(templist)
        grad=nd.Gradient(Function)([xy[0],xy[1]])
        norm=np.linalg.norm(grad)
    return (listofalliter)

f=lambda x,y:np.cos(x)+np.sin(y)+(1/5)*x**2+(1/4)*y**2
xlist=np.linspace(-10,10,1000)
ylist=np.linspace(-10,10,1000)
X,Y=np.meshgrid(xlist,ylist)
Z=f(X,Y)
plt.contourf(X,Y,Z,cmap ="bone")
x0_1=[7,7]
x0_2=[-7,-7]
x0_3=[0,-7]

x1=GradienDecent(f,x0_1)
x0_1listofx=[]
x0_1listofy=[]
for i in range(0,len(x1)):
    x0_1listofx.append(x1[i][0][0])
    x0_1listofy.append(x1[i][0][1])
x1iter=x1[len(x1)-1][2]
x1xmin=x1[len(x1)-1][0][0]
x1ymin=x1[len(x1)-1][0][1]
x1zmin=x1[len(x1)-1][1]
xyz1=[x1xmin,x1ymin,x1zmin]

x2=GradienDecent(f,x0_2)
x0_2listofx=[]
x0_2listofy=[]
for i in range(0,len(x2)):
    x0_2listofx.append(x2[i][0][0])
    x0_2listofy.append(x2[i][0][1])
x2iter=x2[len(x2)-1][2]
x2xmin=x2[len(x2)-1][0][0]
x2ymin=x2[len(x2)-1][0][1]
x2zmin=x2[len(x2)-1][1]
xyz2=[x2xmin,x2ymin,x2zmin]

x3=GradienDecent(f,x0_3)
x0_3listofx=[]
x0_3listofy=[]
for i in range(0,len(x3)):
    x0_3listofx.append(x3[i][0][0])
    x0_3listofy.append(x3[i][0][1])
x3iter=x3[len(x3)-1][2]
x3xmin=x3[len(x3)-1][0][0]
x3ymin=x3[len(x3)-1][0][1]
x3zmin=x3[len(x3)-1][1]
xyz3=[x3xmin,x3ymin,x3zmin]

print("For Start Point Of [7,7] Made: "+str(x1iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz1))
print("For Start Point Of [-7,-7] Made: "+str(x2iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz2))
print("For Start Point Of [0,-7] Made: "+str(x3iter)+" "+"Iterations, The Minimum Is [X,Y,Z]: "+str(xyz3))
print("The End.")
plt.plot(x0_1listofx,x0_1listofy,color='green',marker='.',markersize=2,linestyle='None',label="For Start Point Of [7,7]")
plt.plot(x0_2listofx,x0_2listofy,color='blue',marker='.',markersize=2,linestyle='None',label="For Start Point Of [-7,-7]")
plt.plot(x0_3listofx,x0_3listofy,color='red',marker='.',markersize=2,linestyle='None',label="For Start Point Of [0,-7]")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Gradient Descent For F(x,y):")
plt.colorbar()
plt.legend()
plt.show()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM