【问题标题】:How to avoid plotting for a zero without deleting the zero entry in the line plot Matplotlib?如何避免在不删除线图 Matplotlib 中的零条目的情况下绘制零?
【发布时间】:2021-06-28 16:32:28
【问题描述】:

我尝试了一个示例代码,我用我的图形来绘制:

import matplotlib.pyplot as plt
import numpy as np

l = [1.10867,1.10894,1.10914,1.10926,1.10930,0.00000,0.00000,0.00000,0.00000,0.00000,1.10867,1.10894,1.10914,1.10926,1.10930]
x = np.arange(len(l))
y = np.array(l)

plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma
fig.canvas.draw()
fig.canvas.flush_events()

出来的图如下:

但我希望有一个这样的数字:

当我从列表中删除零时获得了预期的数字。但是我想如果有一种方法可以在不从列表中删除零的情况下进行绘图,并且该图仍然看起来像预期的那样。

请分享任何想法。

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    您可以插入 y 等于 0 的点并绘制:

    import matplotlib.pyplot as plt
    import numpy as np
    
    l = [1.10867,1.10894,1.10914,1.10926,1.10930,0.00000,0.00000,0.00000,0.00000,0.00000,1.10867,1.10894,1.10914,1.10926,1.10930]
    x = np.arange(len(l))
    y = np.array(l)
    
    
    y_interp = np.interp(x, x[np.where(y != 0)], y[np.where(y != 0)])
    plt.plot(x, y_interp)
    

    【讨论】:

    • @BigBen 我猜 OP 说:“当我从列表中删除零时获得了预期的数字。但是如果有一种方法可以在不删除零的情况下进行绘图......”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2020-10-23
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多