[英]matplotlib: How to conditionally plot a histogram from a 2d array
我有一個2D數組,在這里我試圖在給定另一列的條件的情況下繪制一列中所有行的直方圖。 我正在嘗試在plt.hist()命令中選擇子數據,以避免制作許多子數組,而我已經知道該怎么做。 例如,如果
a_long_named_array = [1, 5]
[2, 6]
[3, 7]
我可以通過寫以下內容來創建數組的子集,使第一列大於5
a_long_named_subarray = a_long_named_array[a_long_named_array[:,1] > 5]
如何在不制作上述子數組的情況下繪制此子數據? 請看下面。
import numpy as np
import matplotlib.pyplot as plt
#Generate 2D array
arr = np.array([np.random.random_integers(0,10, 10), np.arange(0,10)])
#Transpose it
arr = arr.T
#----------------------------------------------------------------------------
#Plotting a Histogram: This works
#----------------------------------------------------------------------------
#Plot all the rows of the 0'th column
plt.hist(arr[:,0])
plt.show()
#----------------------------------------------------------------------------
#Plotting a conditional Histogram: This is what I am trying to do. This Doesn't work.
#----------------------------------------------------------------------------
#Plot all the rows of the 0th column where the 1st column is some condition (here > 5)
plt.hist(arr[:,0, where 1 > 5])
plt.show()
quit()
您只需要將布爾值索引( whatever > 5
返回布爾值數組)應用於第一個維度。
您目前正在嘗試使用布爾蒙版沿第三個維度索引數組。 該數組只有2D,因此您可能會得到IndexError
。 (很可能是“ IndexError: too many indices
”。)
例如:
import numpy as np
# Your example data
arr = np.array([np.random.random_integers(0,10, 10), np.arange(0,10)])
arr = arr.T
# What you want:
print arr[arr[:,1] > 5, 0]
基本上,代替:
,您只需放入布爾掩碼( something > 5
)。 您可能會發現寫起來更清晰:
mask = arr[:,1] > 5
result = arr[mask, 0]
另一種思考方式是:
second_column = arr[:,1]
first_column = arr[:,0]
print first_column[second_column > 5]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.