1

I have some python code that applies a 2-D function over a range of x and y values, and uses matplotlib to plot the results as a colormap. However, the axes on this plot show the integer indexes of the output array. I would instead like these axes to show the range of the x and y values, from -1.0 to 1.0, like a typical graphing application would look.

How do I set the range of the axes?

import matplotlib.pyplot as plt

# let x, y values be in range of (-1, 1)
x, y = np.mgrid[-1:1:.05, -1:1:.05]

# Apply the function to the values
z = x * y

# Get matplotlib figure and axis
fig, ax = plt.subplots(figsize=(3, 3), ncols=1)

# Plot the colormap
pos_neg_clipped = ax.imshow(z, cmap='RdBu', interpolation='none')

# Display the image
plt.show()

Output:

Output Image

Wilson
  • 399
  • 2
  • 10

1 Answers1

1

Instead of using imshow, which should only really be used for plotting images, use pcolormesh, which you can pass the x and y values for the axes.

import numpy as np
import matplotlib.pyplot as plt

plt.close("all")

x, y = np.mgrid[-1:1:0.05, -1:1:0.05]
z = x*y

fig, ax = plt.subplots()
ax.pcolormesh(x, y, z, cmap="RdBu")
ax.set_aspect(1)
fig.show()

enter image description here

jared
  • 4,165
  • 1
  • 8
  • 31