使用 matplotlib 制作图形时,如何选择范围?

刘成民

以防万一,将 numpy 导入为 np import matplotlib.pyplot as plt

x = np.linspace(0, 10, 20)
y = x**2 + 2

通常为 plt.plot(x,y) 制作图形,但我有无用的部分。我认为这是创建新数组然后追加。

t = np.array([])
for i in range(len(x)):
    if 4 < i and i < 9:
        continue
    t = np.append(t,x[i])

plt.plot(t,y)

或 new_x = np.array([])

for i in range(len(x)):
    if 4<i and i<9:
        new_x = np.delete(x,i)
plt.plot(new_x,y)

所以,我可以删除无用的部分。有人知道更多关于工作时间的好主意吗?我有海量数据。

热罗尼莫

是否plt.xlim(4, 9)你想要做什么?这只是限制了显示的区域,您仍然可以传递所有数据。


好的,所以如果你真的需要切出有趣的部分,以下可能是一种方法。请注意,它通过 x 的值而不是索引来限制数据,如您的示例所示。

x = np.linspace(0, 10, 20)
y = x**2 + 2
interesting_indices = np.argwhere(np.logical_and(x > 4, x < 9))

plt.plot(x[interesting_indices], y[interesting_indices])

进一步的想法:

  • 始终尝试使用 numpy 的内置元素操作,而不是在 Python 本身中循环项目。传递调用后,numpy 在其基于 C 和 Fortran 的内核中计算和处理数据,这通常会带来更好的性能。
  • 使用时np.append,它总是返回旧数组的副本,大小增加 1,然后删除旧数组。这是大量的内存分配和再次释放,因此非常低效。在性能方面,最好使用一个list

    a2 = [val for val in x if 4 < val < 9]

  • 请记住也y以与reduce相同的方式减少x,否则 plot 无法将数据彼此匹配。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章