【问题标题】:Numpy Array Slicing using a polygon in Matplotlib在 Matplotlib 中使用多边形进行 Numpy 数组切片
【发布时间】:2013-03-22 01:03:39
【问题描述】:

这似乎是一个相当简单的问题,但我是 Python 新手,我正在努力解决它。我有一个从两个 numpy 数组(大约 25,000 条信息)生成的散点图/热图。 y 轴直接取自一个数组,x 轴是通过对两个数组进行简单的减法运算生成的。

我现在需要做的是对数据进行切片,以便我可以使用图上某些参数范围内的选择。例如,我需要提取所有落在平行四边形内的点:

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

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

理想情况下,我确实需要类似于下面的索引的东西,即像 colorjh[idx] 这样的东西。最终我将不得不绘制不同的数量(例如,colorjh[idx]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 的新手,所以解释越少行话,我就越有可能实现它。感谢大家提供的任何帮助。

【问题讨论】:

  • 不回答您的问题,但您的行:mag = list([twomass['m']]); mag = np.array(mag) 可以组合:mag = np.array([twomass['m']]) 没有中间 list,这会更慢并浪费内存。此外,jmag - hmag 已经是一个数组,因此无需调用np.array(jmag - hmag)
  • 附带说明,如果您担心确保事物是数组 np.asarray 很好。

标签: numpy matplotlib polygon slice astronomy


【解决方案1】:
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)

【讨论】:

  • 感谢您的意见。你能解释一下 meshgrid 和 np.logical_and 线发生了什么吗?它看起来像一个优雅的解决方案,但我无法弄清楚如何将它应用到我的代码中。快速尝试产生了 ValueError:“新数组的总大小必须保持不变。”我正在使用的数组都是单值......它们不是矩阵。如果这有任何意义。
  • 代替我的xy 向量,使用你的hh-j 数组。每个h 向量不能只有一个索引,因为h 中的切片取决于您正在查看h-j 中的哪个值,因为它不是矩形,因此您需要在之后创建一个二维矩阵全部。
猜你喜欢
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 2023-04-03
  • 2019-03-25
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多