Change values on matplotlib imshow() graph axis Change values on matplotlib imshow() graph axis numpy numpy

Change values on matplotlib imshow() graph axis


I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here


I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt# ... define 2D array hist as you didplt.imshow(hist, cmap='Reds')x = np.arange(80,122,2) # the grid to which your data correspondsnx = x.shape[0]no_labels = 7 # how many labels to see on axis xstep_x = int(nx / (no_labels - 1)) # step between consecutive labelsx_positions = np.arange(0,nx,step_x) # pixel count at label positionx_labels = x[::step_x] # labels you want to seeplt.xticks(x_positions, x_labels)# in principle you can do the same for y, but it is not necessary in your case