python 为什么绘制串联数组时要添加一条对角线?

cbwuti44  于 2023-03-16  发布在  Python
关注(0)|答案(1)|浏览(116)

我有三个阵列:x_leftx_righty
我用最上面的子情节

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. plt.plot(x_left, y)
  4. plt.plot(x_right, y)

而对于底部子图,

  1. plt.plot(np.concatenate((x_left, x_right)), np.concatenate((y, y)))

为什么在底部的图中有一条从红点开始的对角线?我怎样才能去掉它?

thtygnil

thtygnil1#

发生此错误的原因是x_left是从左到右排序的,而x_right是从右到左排序的。请考虑x_left = np.linspace(-1, 0, 11)x_right = -x_left。当您连接x_leftx_right时,将得到

  1. array([-1. , -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0. ,
  2. 1. , 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, -0. ])

注意到从01的跳跃了吗?这是对角线。
要解决这个问题,对连接的x数组进行排序,当然,你也需要对连接的y数组进行相同的排序:

  1. x_plot = np.concatenate((x_left, x_right))
  2. sort_order = x_plot.argsort()
  3. y_plot = np.concatenate((y, y))
  4. plt.plot(x_plot[sort_order], y_plot[sort_order])

下面是分别绘制它们、连接而不排序和连接并排序(如上图所示)的图形:

  1. x_left = np.linspace(-1, 0, 11)
  2. y = 1 - x_left**2
  3. x_right = -x_left
  4. fig, ax = plt.subplots(1, 3, figsize=(11, 3.5))
  5. ax[0].plot(x_left, y)
  6. ax[0].plot(x_right, y)
  7. ax[0].set_title("Plot separately")
  8. x_plot = np.concatenate((x_left, x_right))
  9. y_plot = np.concatenate((y, y))
  10. sort_order = x_plot.argsort()
  11. ax[1].plot(x_plot, y_plot)
  12. ax[1].set_title("Plot concatenated")
  13. ax[2].plot(x_plot[sort_order], y_plot[sort_order])
  14. ax[2].set_title("Plot concatenated+sorted")
  15. fig.tight_layout()

(for在此图中,我使用y = 1 - x_left**2,因为您没有在问题中提供数据)

展开查看全部

相关问题