2

I copied from this website (and simplified) the following code to plot the result of a function with two variables using imshow.

from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show

# the function that I'm going to plot
def z_func(x,y):
return (x+y**2)

x = arange(-3.0,3.0,0.1)
y = arange(-3.0,3.0,0.1)
X,Y = meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid

im = imshow(Z,cmap=cm.RdBu) # drawing the function

colorbar(im) # adding the colobar on the right
show()

Plot without axis labels

How do I add axis labels (like 'x' and 'y' or 'var1 and 'var2') to the plot? In R I would use xlab = 'x' within (most of) the plotting function(s).

I tried im.ylabel('y') with the

AttributeError: 'AxesImage' object has no attribute 'ylabel'

Beside this, I only found how to remove the axis labels, but not how to add them.

Bonus question: how to have the ticks range from -3 to 3 and not from 0 to 60?

sentence
  • 8,213
  • 4
  • 31
  • 40
Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • Maybe you can try : `set_xlabel()` and `set_ylabel()` https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xlabel.html https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_ylabel.html – Jona May 09 '19 at 15:08
  • I don't think `pylab` is recommended anymore, `pyplot` should be used instead - see [this Q/A](https://stackoverflow.com/questions/11469336/what-is-the-difference-between-pylab-and-pyplot). If you insist on pylab you can always add `ylabel` and `xlabel` to your list of imports, `from pylab import ylabel`; `ylabel("y axis")` – DavidG May 09 '19 at 15:10
  • @Jona `im.set_xlabel('x')` gives a similar error: `AttributeError: 'AxesImage' object has no attribute 'set_xlabel'` – Qaswed May 09 '19 at 15:12

1 Answers1

4

To specify axes labels:

Regarding your bonus question, consider extent kwarg. (Thanks to @Jona).

Moreover, consider absolute imports as recommended by PEP 8 -- Style Guide for Python Code:

Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path)


import matplotlib.pyplot as plt
import numpy as np

# the function that I'm going to plot
def z_func(x,y):
    return (x+y**2)

x = np.arange(-3.0,3.0,0.1)
y = np.arange(-3.0,3.0,0.1)
X,Y = np.meshgrid(x, y) # grid of point
Z = z_func(X, Y) # evaluation of the function on the grid

plt.xlabel('x axis')
plt.ylabel('y axis')

im = plt.imshow(Z,cmap=plt.cm.RdBu, extent=[-3, 3, -3, 3]) # drawing the function

plt.colorbar(im) # adding the colobar on the right
plt.show()

and you get:

enter image description here

sentence
  • 8,213
  • 4
  • 31
  • 40