Pcolormesh没有得到正确的位置matplotlib

时间:2016-05-04 07:06:28

标签: python matplotlib

我正在使用以下代码在png图像上绘制数据:

x, y = np.genfromtxt('pogba_t1314.csv', delimiter=',', unpack=True)

print(x[1], y[1])
y = y[np.logical_not(np.isnan(y))]
x = x[np.logical_not(np.isnan(x))]
k = gaussian_kde(np.vstack([x, y]))
xi, yi = np.mgrid[x.min():x.max():x.size**0.5*1j,y.min():y.max():y.size**0.5*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))

fig = plt.figure(figsize=(9,10))
ax1 = fig.add_subplot(211)

ax1.pcolormesh(xi, yi, zi.reshape(xi.shape), alpha=0.5)

ax1.plot(y,x, "o")
ax1.set_xlim(0, 740)
ax1.set_ylim(515, 0)

im = plt.imread('statszone_football_pitch.png')
ax1.imshow(im, extent=[0, 740, 0, 515], aspect='auto')

结果如下:

enter image description here

Pcolormesh应该在整个图像上,但事实并非如此。我该如何设置正确的位置? 为什么我得到更小的pcolormesh尊重整个音高?我应该有这样的东西(即使这指的是contourf):

enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码似乎运行正常。问题在于,图像中代表x轴的不是你在图中给出的x轴。如果你把x改为y(反之亦然),你就会得到正确的情节:

from scipy.stats.kde import gaussian_kde
import matplotlib.pyplot as plt
import numpy as np

x, y = np.genfromtxt('pogba_t1314.csv', delimiter=',', unpack=True)

print(x[1], y[1])
y = y[np.logical_not(np.isnan(y))]
x = x[np.logical_not(np.isnan(x))]
k = gaussian_kde(np.vstack([x, y]))
#xi, yi = np.mgrid[x.min():x.max():x.size**0.5*1j,y.min():y.max():y.size**0.5*1j]
xi, yi = np.mgrid[y.min():y.max():y.size**0.5*1j,x.min():x.max():x.size**0.5*1j] # Changed this.
#zi = k(np.vstack([xi.flatten(), yi.flatten()]))
zi = k(np.vstack([yi.flatten(),xi.flatten()])) # And this.

fig = plt.figure(figsize=(9,10))
ax1 = fig.add_subplot(111)

ax1.pcolormesh(xi, yi, zi.reshape(xi.shape), alpha=0.5)

ax1.plot(y,x, "o")
ax1.set_xlim(0, 740)
ax1.set_ylim(515, 0)

im = plt.imread('statszone_football_pitch.jpg')
ax1.imshow(im, extent=[0, 740, 0, 515], aspect='auto')
plt.show()

结果如下:

pcolormesh over image

我猜这是你散乱点的一种密度图。