2017-06-15 109 views
1

我一直在嘗試使用matplotlib向我的情節添加垂直線,然後在它們之間添加填充。如何從文件繪製多條垂直線?

  • thresh_f是文件名
  • thresh_f有兩列只有

下面的代碼將有錯誤時,該文件有一個以上的線

start, end = np.loadtxt(thresh_f, usecols = [0,1], unpack = True) 
ax.axvspan(start, end, alpha=0.3, color='y') 

我得到錯誤:

'bool' object has no attribute 'any'

我無法理解這是什麼意思。

回答

2

問題是,當文件多於一行時,變量startend成爲數組。你要提高你的代碼,如:

start, end = np.loadtxt(thresh_f, usecols = [0,1], unpack = True) 
ax = plt.gca() 
print (start, end) # test data [ 0. 5.] [ 1. 6.] 
# check the type of start variable 
# loadtxt may return np.ndarray variable 
if type(start) is list or type(start) is tuple or type(start) is np.ndarray: 
    for s, e in zip(start, end): 
     ax.axvspan(s, e, alpha=0.3, color='y') # many rows, iterate over start and end 
else: 
    ax.axvspan(start, end, alpha=0.3, color='y') # single line 

plt.show() 

enter image description here

+0

啊謝謝你這麼多。完美的作品。謝謝你解釋原因! :) –

2

如果你想避免if - else聲明,您可以通過ndmin = 2np.loadtext()。這可以確保您的startend總是可迭代的。

import numpy as np 
from matplotlib import pyplot as plt 

fig, ax = plt. subplots(1,1) 

thresh_f = 'thresh_f.txt' 
starts, ends = np.loadtxt(thresh_f, usecols = [0,1], unpack = True, ndmin = 2) 

for start, end in zip(starts, ends): 
    ax.axvspan(start, end, alpha=0.3, color='y') 

plt.show() 

這裏的結果的文本之一,兩行:

+0

這也很好。謝謝! –