我一直在尝试使用matplotlib为我的绘图添加垂直线,然后在它们之间添加填充。
当文件有多行
时,下面的代码会出错start, end = np.loadtxt(thresh_f, usecols = [0,1], unpack = True)
ax.axvspan(start, end, alpha=0.3, color='y')
我收到错误:
'bool'对象没有属性'any'
我无法理解这意味着什么。
答案 0 :(得分:2)
The problem is that your variables start
and end
become arrays when file has more then one lines. You have to improve your code like:
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()
答案 1 :(得分:2)
If you want to avoid the if
-else
statement, you can pass ndmin = 2
to np.loadtext()
. This assures that your start
and end
are always iterable.
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()
Here the results for one and two lines of text: