【问题标题】:Plotting tolerance bars in python matplotlib在 python matplotlib 中绘制公差条
【发布时间】:2018-08-16 21:15:31
【问题描述】:

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

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()

不幸的是,我不太了解 pyton,无法理解带星号的表达式或 zip 函数,但它似乎将 X 值分组为一个元组,将 Y 值分组为一个元组。

我想在ref 周围添加 10% 的公差线。我知道这应该可行:

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”类型的非整数。

我已经试过了:

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

TypeError: len() of unsized object

如何将ref 翻译成我可以使用的东西?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以使用ref_y;这是一个清单。要将列表乘以纯 Python 中的常数,您需要将该列表的每个元素乘以该常数 new_data = [x*0.9 for x in old_data]

    更简单的解决方案是立即使用 numpy 数组。

    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()
    

    【讨论】:

    • 我们的时间完全同步 ;) 顺便说一句,我意识到你的用户名中有一个 import
    • 是的,我通常每天早上都会做import anceOfBeingErnst as me。 :-P
    【解决方案2】:

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

    首先,创建两个列表作为上限和下限,并使用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)
    

    输出(res 现在被您的误差线/填充区域覆盖,因为在这种情况下 10% 似乎太多了。):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 2018-05-18
      • 2022-01-27
      • 2019-10-17
      • 2015-06-06
      • 1970-01-01
      相关资源
      最近更新 更多