2017-06-15 107 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

这也很好。谢谢! –