0

我目前正在一个情节中工作,我在其中显示数据组合。我用以下代码绘制它们:

plt.figure()

# Data 1
data = plt.cm.binary(data1)
data[..., 3] = 1.0 * (data1 > 0.0)
fig = plt.imshow(data, interpolation='nearest', cmap='binary', vmin=0, vmax=1, extent=(-4, 4, -4, 4))

# Plotting just the nonzero values of data2
x = numpy.linspace(-4, 4, 11)
y = numpy.linspace(-4, 4, 11)
data2_x = numpy.nonzero(data2)[0]
data2_y = numpy.nonzero(data2)[1]

pts = plt.scatter(x[data2_x], y[data2_y], marker='s', c=data2[data2_x, data2_y])

这给了我这个情节:

在此处输入图像描述

如图所示,我的背景和前景方块没有对齐。

然后两者都具有相同的尺寸(20 x 20)。如果可能的话,我希望有一种方法可以将中心与中心对齐,或者将角与角对齐,但要进行某种对齐。

在某些网格单元格中,我似乎有右下角对齐,在其他左下角对齐中,在其他网格单元中根本没有对齐,这会降低可视化效果。

任何帮助,将不胜感激。

谢谢你。

4

2 回答 2

2

As tcaswell says, your problem may be easiest to solve by defining the extent keyword for imshow.

If you give the extent keyword, the outermost pixel edges will be at the extents. For example:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(np.random.random((8, 10)), extent=(2, 6, -1, 1), interpolation='nearest', aspect='auto')

enter image description here

Now it is easy to calculate the center of each pixel. In X direction:

  • interpixel distance is (6-2) / 10 = 0.4 pixels
  • center of the leftmost pixel is half a pixel away from the left edge, 2 + .4/2 = 2.2

Similarly, the Y centers are at -.875 + n * 0.25.

So, by tuning the extent you can get your pixel centers wherever you want them.


An example with 20x20 data:

import matplotlib.pyplot as plt
import numpy

# create the data to be shown with "scatter"
yvec, xvec = np.meshgrid(np.linspace(-4.75, 4.75, 20), np.linspace(-4.75, 4.75, 20))
sc_data = random.random((20,20))

# create the data to be shown with "imshow" (20 pixels)
im_data = random.random((20,20))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(im_data, extent=[-5,5,-5,5], interpolation='nearest', cmap=plt.cm.gray)
ax.scatter(xvec, yvec, 100*sc_data)

enter image description here

Notice that here the inter-pixel distance is the same for both scatter (if you have a look at xvec, all pixels are 0.5 units apart) and imshow (as the image is stretched from -5 to +5 and has 20 pixels, the pixels are .5 units apart).

于 2014-07-18T22:34:24.283 回答
1

这是一个没有对齐问题的代码。

import matplotlib.pyplot as plt
import numpy

data1 = numpy.random.rand(10, 10)
data2 = numpy.random.rand(10, 10)
data2[data2 < 0.4] = 0.0

plt.figure()

# Plotting data1
fig = plt.imshow(data1, interpolation='nearest', cmap='binary', vmin=0.0, vmax=1.0)

# Plotting data2
data2_x = numpy.nonzero(data2)[0]
data2_y = numpy.nonzero(data2)[1]
pts = plt.scatter(data2_x, data2_y, marker='s', c=data2[data2_x, data2_y])

plt.show()

这给出了一个完美对齐的组合图:

对齐的地块

因此,在您的代码中使用附加选项可能是组合图未对齐的原因。

于 2014-07-18T22:55:15.927 回答