2013-03-31 26 views
4

这似乎是一个相当直接的问题,但我是Python的新手,我正在努力解决它。我有一个由两个numpy数组产生的散点图/热图(大约25,000条信息)。 y轴直接取自一个数组,x轴由两个数组上的简单减法运算生成。Numpy Array在Matplotlib中使用多边形切片

我现在需要做的是切片数据,以便我可以使用属于图上特定参数的选择。例如,我需要提取所有属于平行四边形内的点: enter image description here

我能切出使用简单的不等式矩形(见下面的索引idx_cidx_hidx,),但我真的需要一个使用更复杂的几何体来选择点的方法。看起来这种切片可以通过指定多边形的顶点来完成。这是关于最接近我能找到一个解决方案,但我想不出如何实现它:

http://matplotlib.org/api/nxutils_api.html#matplotlib.nxutils.points_inside_poly

理想情况下,我真的需要一个类似于下面的索引,即像colorjh[idx]。最终,我必须绘制不同的数量(例如,colorjh[idx] vs colorhk[idx]),因此索引需要可转移到数据集中的所有数组(大量数组)。也许这很明显,但我会想象有些解决方案可能不那么灵活。换句话说,我将使用这个图来选择我感兴趣的点,然后我需要这些索引为来自同一个表的其他数组工作。

这里是我的工作代码:

import numpy as np 
from numpy import ndarray 
import matplotlib.pyplot as plt 
import matplotlib 
import atpy 
from pylab import * 

twomass = atpy.Table() 

twomass.read('/IRSA_downloads/2MASS_GCbox1.tbl') 

hmag = list([twomass['h_m']]) 
jmag = list([twomass['j_m']]) 
kmag = list([twomass['k_m']]) 

hmag = np.array(hmag) 
jmag = np.array(jmag) 
kmag = np.array(kmag) 

colorjh = np.array(jmag - hmag) 
colorhk = np.array(hmag - kmag) 

idx_c = (colorjh > -1.01) & (colorjh < 6) #manipulate x-axis slicing here here 
idx_h = (hmag > 0) & (hmag < 17.01)  #manipulate y-axis slicing here 
idx = idx_c & idx_h 

# heatmap below 
heatmap, xedges, yedges = np.histogram2d(hmag[idx], colorjh[idx], bins=200) 
extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]] 
plt.clf() 
plt.imshow(heatmap, extent=extent, aspect=0.65) 

plt.xlabel('Color(J-H)', fontsize=15)   #adjust axis labels here 
plt.ylabel('Magnitude (H)', fontsize=15) 

plt.gca().invert_yaxis()  #I put this in to recover familiar axis orientation 

plt.legend(loc=2) 
plt.title('CMD for Galactic Center (2MASS)', fontsize=20) 
plt.grid(True) 
colorbar() 

plt.show() 

就像我说的,我是新来的Python,所以少行话-Y的解释越有可能我就可以实现它。谢谢你们可以提供的任何帮助。

+0

不回答你的问题,但你的台词:'MAG =名单([twomass [ 'M']); mag = np.array(mag)'可以合并:'mag = np.array([twomass ['m']])''没有中间'list',这会更慢并且浪费内存。另外,'jmag-hmag'已经是一个数组了,所以不需要调用'np.array(jmag - hmag)'。 – askewchan

+0

作为一个方面说明,如果你担心确保数组'np.asarray'很好。 – tacaswell

回答

2
a = np.random.randint(0,10,(100,100)) 

x = np.linspace(-1,5.5,100) # tried to mimic your data boundaries 
y = np.linspace(8,16,100) 
xx, yy = np.meshgrid(x,y) 

m = np.all([yy > xx**2, yy < 10* xx, xx < 4, yy > 9], axis = 0) 

enter image description here

+0

感谢您的输入。你能解释一下meshgrid和np.logical_and行是怎么回事?它看起来像一个优雅的解决方案,但我不知道如何将这个工作到我的代码中。 快速尝试产生了一个ValueError:“新数组的总大小必须保持不变。”我正在使用的数组都是单值...他们不是矩阵。如果那有意义的话。 – Teachey

+0

使用你的'h'和'h-j'数组代替我的'x'和'y'向量。每个'h'向量不能只有一个索引,因为'h'中的切片取决于您正在查看的'hj'中的哪个值,因为它不是矩形的,所以您需要在之后创建一个2d矩阵所有。 – askewchan