2017-06-15 22 views
1

matplotlibを使ってプロットに縦線を加え、その間に塗りつぶしを追加しようとしました。ファイルから複数の垂直線をプロットする方法は?

  • thresh_fは、ファイルの名前でファイルが

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

    は私が得る複数のラインを持っている場合、コードは以下のエラーを持つことになりますのみ

2つの列がありthresh_f

  • エラー:

    'bool' object has no attribute 'any'

    私はそれが意味することを理解する手がかりがありません。

  • 答えて

    2

    問題は、変数startendがファイルに複数の行がある場合に配列になるという問題です。 else声明、あなたがnp.loadtext()ndmin = 2を渡すことができます - あなたはifを避けたい場合は

    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

    :あなたは次のようにコードを改善する必要があります。これにより、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() 
    

    ここでは、テキストの1と2行の結果:

    +0

    これはまた素晴らしい動作します。ありがとうございました! –

    関連する問題