use*_*455 5 numpy matplotlib python-2.7
我有一个庞大的数据集,我需要将图分成网格并计算每个网格方块内的点数。我正在遵循此处概述的方法:
下面是我的代码的精简版本:
import numpy as np
import matplotlib.pyplot as plt
x = [ 1.83259571, 1.76278254, 1.38753676, 1.6406095, 1.34390352, 1.23045712, 1.85877565, 1.26536371, 0.97738438]
y = [ 0.04363323, 0.05235988, 0.09599311, 0.10471976, 0.1134464, 0.13962634, 0.17453293, 0.20943951, 0.23561945]
gridx = np.linspace(min(x),max(x),11)
gridy = np.linspace(min(y),max(y),11)
grid, _, _ = np.histogram2d(x, y, bins=[gridx, gridy])
plt.figure()
plt.plot(x, y, 'ro')
plt.grid(True)
plt.figure()
plt.pcolormesh(gridx, gridy, grid)
plt.plot(x, y, 'ro')
plt.colorbar()
plt.show()
Run Code Online (Sandbox Code Playgroud)
出现问题的地方是网格将绘图的元素识别为点出现的位置,但其中一些元素中没有点;同样,当出现一些实际数据点时,网格不会将它们识别为实际上不存在。
可能是什么原因导致这个问题?另外,很抱歉没有附上剧情,我是新用户,我的声誉还不够高。
更新 这是生成 100 个随机点并尝试将它们绘制在二维直方图中的代码:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
gridx = np.linspace(0,1,11)
gridy = np.linspace(0,1,11)
grid, __, __ = np.histogram2d(x, y, bins=[gridx, gridy])
plt.figure()
plt.plot(x, y, 'ro')
plt.grid(True)
plt.figure()
plt.pcolormesh(gridx, gridy, grid)
plt.plot(x, y, 'ro')
plt.colorbar()
plt.show()
Run Code Online (Sandbox Code Playgroud)
然而,当我运行它时,我遇到了与以前相同的问题:点的位置和点位置密度对应的颜色不一致。当有人自己运行这段代码时会发生这种情况吗?
第二次更新
冒着死马的风险,这里有一个参数图的代码:
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0,1,100)
x = np.sin(t)
y = np.cos(t)
gridx = np.linspace(0,1,11)
gridy = np.linspace(0,1,11)
#grid, __, __ = np.histogram2d(x, y, bins=[gridx, gridy])
grid, __, __ = np.histogram2d(x, y)
plt.figure()
plt.plot(x, y, 'ro')
plt.grid(True)
plt.figure()
plt.pcolormesh(gridx, gridy, grid)
plt.plot(x, y, 'ro')
plt.colorbar()
plt.show()
Run Code Online (Sandbox Code Playgroud)
这让我觉得这都是某种奇怪的缩放问题。但还是彻底迷失了……
我能够通过使用带有插值的 imshow 而不是 pcolormesh 来使您的示例正常工作。请参阅下面的示例代码。
我认为问题可能是 pcolormesh 的起源约定与绘图不同。pcolormesh的结果看起来左上和右下翻转了。
imshow 的结果如下所示:
示例代码:
import numpy as np
import matplotlib.pyplot as plt
def doPlot():
x = [ 1.83259571, 1.76278254, 1.38753676, 1.6406095, 1.34390352, 1.23045712, 1.85877565, 1.26536371, 0.97738438]
y = [ 0.04363323, 0.05235988, 0.09599311, 0.10471976, 0.1134464, 0.13962634, 0.17453293, 0.20943951, 0.23561945]
gridx = np.linspace(min(x),max(x),11)
gridy = np.linspace(min(y),max(y),11)
H, xedges, yedges = np.histogram2d(x, y, bins=[gridx, gridy])
plt.figure()
plt.plot(x, y, 'ro')
plt.grid(True)
#wrong origin convention for pcolormesh?
#plt.figure()
#plt.pcolormesh(gridx, gridy, H)
#plt.plot(x, y, 'ro')
#plt.colorbar()
plt.figure()
myextent =[xedges[0],xedges[-1],yedges[0],yedges[-1]]
plt.imshow(H.T,origin='low',extent=myextent,interpolation='nearest',aspect='auto')
plt.plot(x,y,'ro')
plt.colorbar()
plt.show()
if __name__=="__main__":
doPlot()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7973 次 |
最近记录: |