2

I am using the following code to generate some contour plots,

from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
import numpy as np
from numpy import exp,arange
import matplotlib.pyplot as plt

def z_func(x,y):
    func = 3.0*(1.0 - x)**2*np.exp(-x**2 - (y+1.0)**2) - 10.0*(x/5.0 - x**3 - y**5)*np.exp(-x**2 - y**2) - 0.33*np.exp(-(x + 1.0)**2 - y**2)
    return func


x = arange(-4.0,4.0,0.1)
y = arange(-4.0,4.0,0.1)
X,Y = meshgrid(x, y) # grid of point
Z = z_func(X, Y)

fig = plt.figure(figsize=(10,6))
im = imshow(Z,cmap=cm.RdBu) # drawing the function
# adding the Contour lines with labels
cset = contour(Z,arange(-1,1.5,0.2),linewidths=2,cmap=cm.Set2)
clabel(cset,inline=True,fmt='%1.1f',fontsize=10)
colorbar(im) # adding the colobar on the right
# latex fashion title
title('peaks function')
show()

I stole it from somehwere on StackExchange. I am having a difficult time simply getting the x and y axes to display the correct domains, [-4,4]. There are a number of solutions already posted that do not work for me such as Change values on matplotlib imshow() graph axis and correcting the axes using imshow but neither keep the image the way it is and relabels the axes. Help!!!

Community
  • 1
  • 1
superhero
  • 185
  • 3
  • 16
  • This code is not working. Do you just want to set axises limits for imshow? – Serenity Jun 13 '16 at 09:02
  • The code works for me. I forgot my imports...let me put in now. I want the axes to reflect the actual bounds for my input variables, [-4,4] – superhero Jun 13 '16 at 09:02

1 Answers1

2

Try this code, you have to set limits in both functions contour and imshow as I did:

import matplotlib.pylab as plt
import numpy as np

x = np.arange(-4.0,4.0,0.1)
y = np.arange(-4.0,4.0,0.1)
X,Y = np.meshgrid(x, y) # grid of point
Z = X**2. * np.sin(Y)

fig = plt.figure(figsize=(10,6))
im = plt.imshow(Z,cmap=plt.cm.RdBu, extent=(-4,4,-4,4)) # drawing the function
# adding the Contour lines with labels
cset = plt.contour(Z,np.arange(-1,1.5,0.2),linewidths=2,cmap=plt.cm.Set2, extent=(-4,4,-4,4))
plt.clabel(cset,inline=True,fmt='%1.1f',fontsize=10)
plt.colorbar(im) # adding the colobar on the right
# latex fashion title
plt.title('peaks function')
plt.show()

enter image description here

There is a problem in your code: Z have to be a 2d array but z_fun_optimization(x) get only one argument.

Serenity
  • 35,289
  • 20
  • 120
  • 115
  • Cutting and pasting error. My fault :-0. Updated code is there. This did it though! I was forgetting to put in the `extent` argument in the contour argument as well. Thanks! – superhero Jun 13 '16 at 09:12