代码之家  ›  专栏  ›  技术社区  ›  hootnot

遮罩级数上的Matplotlib插值

  •  0
  • hootnot  · 技术社区  · 7 年前

    我有一组数据,从中生成3个图(参见示例)。顶部绘图是从一个完整的集合创建的,其他两个是从一个子集创建的。

    我想看到的是,第二个和第三个图中的线是连续的。如何做到这一点? 下面是一个来自 https://scipy-cookbook.readthedocs.io/items/Matplotlib_Plotting_values_with_masked_arrays.html

    enter image description here

    import numpy as np
    import matplotlib.pyplot as plt
    
    # suppose we have full serie of y values and 2 others that can have gaps
    # but always one is available like:
    # y:    10, 20, 30, 40 , 50
    # y2:    1,  4, -,  -  , 12
    # y3:    -,  -, 6,  8  ,  -
    
    y_values = [92,94,100,97,98,102,99,101,97,102,99,105,101]
    # prepare for masking arrays - 'conventional' arrays won't do it
    y_values = np.ma.array(y_values)
    
    # from y artifically create y2 and y2
    # give a threshold
    threshold = 99
    
    y2_values = np.ma.masked_where(y_values < threshold, [v-50 for v in y_values])
    y3_values = np.ma.masked_where(~(y_values < threshold), [v-80 for v in y_values])
    x_values = [0,1,2,3,4,5,6,7,8,9,10,11,12]
    
    fig, ax = plt.subplots(3, sharex=True, facecolor='w')
    fig.subplots_adjust(hspace=0.25)
    
    #plot all data
    ax[0].plot(x_values, y_values) #,'ko')
    ax[0].set_title('All values')
    
    ax[1].plot(x_values, y2_values) #,'ko')
    ax[1].set_title('y2-values')
    #ax = plt.subplot(313)
    
    ax[2].plot(x_values, y3_values) #,'ko')
    ax[2].set_title('y3-values')
    fig.savefig("3sp.png")
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   ImportanceOfBeingErnest    7 年前

    [-- -- 50 -- -- 52 49 51 -- 52 49 55 51]
    

    你可以策划

    [50 52 49 51 52 49 55 51]
    

    mask 它本身

    ax.plot(x_values[~y2_values.mask], y2_values[~y2_values.mask])
    

    完整示例:

    import numpy as np
    import matplotlib.pyplot as plt
    
    y_values = [92,94,100,97,98,102,99,101,97,102,99,105,101]
    y_values = np.ma.array(y_values)
    threshold = 99
    
    y2_values = np.ma.masked_where(y_values < threshold, [v-50 for v in y_values])
    y3_values = np.ma.masked_where(~(y_values < threshold), [v-80 for v in y_values])
    x_values = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12])
    
    fig, ax = plt.subplots(3, sharex=True, facecolor='w')
    fig.subplots_adjust(hspace=0.25)
    
    ax[0].plot(x_values, y_values, marker="o")
    ax[0].set_title('All values')
    
    ax[1].plot(x_values[~y2_values.mask], y2_values[~y2_values.mask], marker="o")
    ax[1].set_title('y2-values')
    
    ax[2].plot(x_values[~y3_values.mask], y3_values[~y3_values.mask], marker="o")
    ax[2].set_title('y3-values')
    plt.show()
    

    enter image description here