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

在python matplotlib中绘制公差条

  •  2
  • Stewart  · 技术社区  · 6 年前

    我现有的代码可以简化为:

    import matplotlib.pyplot as plt
    
    ref = [(0.0, 151.6875), (0.011, 151.75), (0.022, 151.75), (0.031, 151.625), (0.042, 151.625), (0.052, 151.6875), (0.061, 151.625), (0.073, 151.6875), (0.08, 151.625)]
    res = [(0.0, 151.879), (0.01, 151.881), (0.02, 151.882), (0.03, 151.884), (0.04, 151.886), (0.05, 151.887), (0.06, 151.889), (0.07, 151.891), (0.08, 151.892)]
    
    plt.plot(*zip(*res), 'g')
    plt.plot(*zip(*ref), 'b')
    
    plt.show()
    

    不幸的是,我对皮顿的理解还不足以理解他那星光熠熠的表情或者 zip 函数,但它似乎将X值分组为元组,将Y值分组为元组。

    我想在周围加上10%的公差线 ref . 我知道这应该管用:

    plt.fill_between(x, y * 0.9, y * 1.1)
    

    但我不知道如何把ref和res转换成x和y。我试过:

    ref_x, ref_y = zip(*ref)
    plt.fill_between(ref_x, ref_y * 0.9, ref_y * 1.1)
    

    TypeError:不能将序列乘以'float'类型的非int。

    for point in ref :
        plt.fill_between(point[0], point[1] * 0.9, point[1] * 1.1)
    

    类型错误:未调整大小的对象的len()

    我怎么翻译 变成我能用的东西?

    2 回复  |  直到 6 年前
        1
  •  2
  •   ImportanceOfBeingErnest    6 年前

    你可以用 ref_y new_data = [x*0.9 for x in old_data] .

    import matplotlib.pyplot as plt
    
    ref = [(0.0, 151.6875), (0.011, 151.75), (0.022, 151.75), (0.031, 151.625), (0.042, 151.625), (0.052, 151.6875), (0.061, 151.625), (0.073, 151.6875), (0.08, 151.625)]
    res = [(0.0, 151.879), (0.01, 151.881), (0.02, 151.882), (0.03, 151.884), (0.04, 151.886), (0.05, 151.887), (0.06, 151.889), (0.07, 151.891), (0.08, 151.892)]
    
    ref = np.array(ref)
    res = np.array(res)
    
    plt.plot(ref[:,0], ref[:,1], 'g')
    plt.plot(res[:,0], ref[:,1], 'b')
    
    plt.fill_between(ref[:,0], ref[:,1] * 0.9, ref[:,1] * 1.1)
    
    plt.show()
    
        2
  •  1
  •   Sheldore    6 年前

    我认为有两种可能的解决方案:

    首先,创建两个列表作为上下限,并使用 fill_between . 不能直接乘以0.9和1.1的原因是 zip 回报 tuple . 即使您使用 list(ref_y) ,不能同时将列表中的每个元素乘以整数/浮点数,这与使用数组不同:

    lim_down = [0.9*i for i in ref_y]
    lim_up = [1.1*i for i in ref_y]
    plt.fill_between(ref_x, lim_down, lim_up)
    

    第二,将y值转换为数组,这样就可以简单地将它们乘以0.9和1.1,这两个值将应用于每个元素。

    plt.fill_between(ref_x, np.array(ref_y) * 0.9, np.array(ref_y) * 1.1)
    

    enter image description here