代码之家  ›  专栏  ›  技术社区  ›  Axle Max

Matplotlib打印时计算值-python3

  •  0
  • Axle Max  · 技术社区  · 6 年前

    我只想在绘制图形时绘制正值(类似于ML中的RELU函数)

    在下面的代码中,我迭代并更改底层列表数据。我只想在绘图时间更改值,而不更改源列表数据。有可能吗?

    #create two lists in range -10 to 10
    x = list(range(-10, 11))
    y = list(range(-10, 11))
    
    #this function changes the underlying data to remove negative values
    #I really want to do this at plot time
    #I don't want to change the source list. Can it be done?
    for idx, val in enumerate(y):
        y[idx] = max(0, val)
    
    #a bunch of formatting to make the plot look nice
    plt.figure(figsize=(6, 6))
    plt.axhline(y=0, color='silver')
    plt.axvline(x=0, color='silver')
    plt.grid(True)
    
    plt.plot(x, y, 'rx')
    
    plt.show()
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   ImportanceOfBeingErnest    6 年前

    我建议在绘图时使用numpy并过滤数据:

    import numpy as np
    import matplotlib.pyplot as plt
    
    #create two lists in range -10 to 10
    x = list(range(-10, 11))
    y = list(range(-10, 11))
    
    x = np.array(x)
    y = np.array(y)
    
    #a bunch of formatting to make the plot look nice
    plt.figure(figsize=(6, 6))
    plt.axhline(y=0, color='silver')
    plt.axvline(x=0, color='silver')
    plt.grid(True)
    
    # plot only those values where y is positive
    plt.plot(x[y>0], y[y>0], 'rx')
    
    plt.show()
    

    这根本不会用y<0绘制点。如果您希望将任何负值替换为零,可以执行以下操作

    plt.plot(x, np.maximum(0,y), 'rx')
    
        2
  •  0
  •   tif    6 年前

    它看起来可能有点复杂,但可以动态过滤数据:

    plt.plot(list(zip(*[(x1,y1) for (x1,y1) in zip(x,y) if x1>0])), 'rx')