Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

python - Plot 2D array data into figure centered at specific pixel

I have got a figure with with an axis object. I would like to use ax.scatter to scatter something into the plot, which is no problem. On top I want to draw 2D array data into the same figure (using ax.imshow for example...):

import numpy as np
from matplotlib import pyplot as plt

vidRes = np.array([[-700, 700], [-500,500]])
dim = np.array([vidRes[0,1] - vidRes[0,0],vidRes[1,1] - vidRes[1,0]])

with plt.style.context('dark_background'):
    fg = plt.figure()
    fg.set_size_inches((10, 10*dim[1]/dim[0]))
    ax = fg.add_subplot(111)
    ax.set_aspect('equal')
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.set_xlim(vidRes[0,0], vidRes[0,1])
    ax.set_ylim(vidRes[1,0], vidRes[1,1])

random = np.random.random(size = (401, 401,),)
ax.imshow(random, cmap = 'hot')

This is the output

The 2D array has 401x401 entries. Is there a straight forward way to move the imshow object to center it on a given pixel in my 1400x1000 pixel figure? Am I blind to not see it?

The image is drawn into the figure but it is always aligned with the lower left or upper left corner (depending on origin of ax.imshow) to the (0,0) coordinate at the center of my plot, I can't move it anywhere else.

question from:https://stackoverflow.com/questions/66065229/plot-2d-array-data-into-figure-centered-at-specific-pixel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the extent argument. From the docs:

extent : scalars (left, right, bottom, top), optional, default: None The location, in data-coordinates, of the lower-left and upper-right corners. If None, the image is positioned such that the pixel centers fall on zero-based (row, column) indices.

Changing your imshow call to the following line:

ax.imshow(random, cmap = 'hot', extent=[-200.5, 200.5, -200.5, 200.5])

yields:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...