我有三个阵列:x_left、x_right和y我用最上面的子情节
x_left
x_right
y
import numpy as npimport matplotlib.pyplot as pltplt.plot(x_left, y)plt.plot(x_right, y)
import numpy as np
import matplotlib.pyplot as plt
plt.plot(x_left, y)
plt.plot(x_right, y)
而对于底部子图,
plt.plot(np.concatenate((x_left, x_right)), np.concatenate((y, y)))
为什么在底部的图中有一条从红点开始的对角线?我怎样才能去掉它?
thtygnil1#
发生此错误的原因是x_left是从左到右排序的,而x_right是从右到左排序的。请考虑x_left = np.linspace(-1, 0, 11)和x_right = -x_left。当您连接x_left和x_right时,将得到
x_left = np.linspace(-1, 0, 11)
x_right = -x_left
array([-1. , -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0. , 1. , 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, -0. ])
array([-1. , -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0. ,
1. , 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, -0. ])
注意到从0到1的跳跃了吗?这是对角线。要解决这个问题,对连接的x数组进行排序,当然,你也需要对连接的y数组进行相同的排序:
0
1
x
x_plot = np.concatenate((x_left, x_right))sort_order = x_plot.argsort()y_plot = np.concatenate((y, y))plt.plot(x_plot[sort_order], y_plot[sort_order])
x_plot = np.concatenate((x_left, x_right))
sort_order = x_plot.argsort()
y_plot = np.concatenate((y, y))
plt.plot(x_plot[sort_order], y_plot[sort_order])
下面是分别绘制它们、连接而不排序和连接并排序(如上图所示)的图形:
x_left = np.linspace(-1, 0, 11)y = 1 - x_left**2x_right = -x_leftfig, ax = plt.subplots(1, 3, figsize=(11, 3.5))ax[0].plot(x_left, y)ax[0].plot(x_right, y)ax[0].set_title("Plot separately")x_plot = np.concatenate((x_left, x_right))y_plot = np.concatenate((y, y))sort_order = x_plot.argsort()ax[1].plot(x_plot, y_plot)ax[1].set_title("Plot concatenated")ax[2].plot(x_plot[sort_order], y_plot[sort_order])ax[2].set_title("Plot concatenated+sorted")fig.tight_layout()
y = 1 - x_left**2
fig, ax = plt.subplots(1, 3, figsize=(11, 3.5))
ax[0].plot(x_left, y)
ax[0].plot(x_right, y)
ax[0].set_title("Plot separately")
ax[1].plot(x_plot, y_plot)
ax[1].set_title("Plot concatenated")
ax[2].plot(x_plot[sort_order], y_plot[sort_order])
ax[2].set_title("Plot concatenated+sorted")
fig.tight_layout()
(for在此图中,我使用y = 1 - x_left**2,因为您没有在问题中提供数据)
1条答案
按热度按时间thtygnil1#
发生此错误的原因是
x_left
是从左到右排序的,而x_right
是从右到左排序的。请考虑x_left = np.linspace(-1, 0, 11)
和x_right = -x_left
。当您连接x_left
和x_right
时,将得到注意到从
0
到1
的跳跃了吗?这是对角线。要解决这个问题,对连接的
x
数组进行排序,当然,你也需要对连接的y
数组进行相同的排序:下面是分别绘制它们、连接而不排序和连接并排序(如上图所示)的图形:
(for在此图中,我使用
y = 1 - x_left**2
,因为您没有在问题中提供数据)