Python的Matplotlib在错误的ord中绘制

2024-04-29 17:12:46 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我有两个数组,一个包含x轴的值,另一个包含y轴的值。问题是,当我这样做的时候

plt.semilogy(out_samp,error_mc)

我明白了

enter image description here

这没有任何意义。这是因为plot函数在x数组中绘制遇到的所有内容,而不关心是否按升序排序。如何对这两个数组进行排序,以便x数组按递增值排序,y轴按相同的方式排序,以便点相同,但图是连接的,这样就不会造成这种混乱?

提前谢谢你!


Tags: 函数内容排序plot绘制plterror数组
3条回答

排序列表的另一种方法是使用NumPy数组并使用np.sort()进行排序。使用数组的优点是在计算y=f(x)这样的函数时进行矢量化操作。下面是绘制正态分布的示例:

不使用排序数据

mu, sigma = 0, 0.1
x = np.random.normal(mu, sigma, 200)
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(x,f, '-bo', ms = 2)

输出1

enter image description here

使用np.sort()这允许在计算正态分布时直接使用排序数组x

mu, sigma = 0, 0.1
x = np.sort(np.random.normal(mu, sigma, 200)) 
# or use x = np.random.normal(mu, sigma, 200).sort()
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(x,f, '-bo', ms = 2)

或者,如果x和y数据都未排序,则可以使用numpy.argsort对它们进行后验排序

mu, sigma = 0, 0.1
x = np.random.normal(mu, sigma, 200)
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(np.sort(x), f[np.argsort(x)], '-bo', ms = 2)

在这两种情况下,输出都是

输出2

enter image description here

打印前按x轴值排序。这是一个MWE。

import itertools

x = [3, 5, 6, 1, 2]
y = [6, 7, 8, 9, 10]

lists = sorted(itertools.izip(*[x, y]))
new_x, new_y = list(itertools.izip(*lists))

# import operator
# new_x = map(operator.itemgetter(0), lists)        # [1, 2, 3, 5, 6]
# new_y = map(operator.itemgetter(1), lists)        # [9, 10, 6, 7, 8]

# Plot
import matplotlib.pylab as plt
plt.plot(new_x, new_y)
plt.show()

对于小数据,^{}(如其他回答者所述)就足够了。

new_x, new_y = zip(*sorted(zip(x, y)))

结果是

enter image description here

更容易对这两个数据列表进行zip、排序和取消zip

示例:

xs = [...]
ys = [...]

xs, ys = zip(*sorted(zip(xs, ys)))

plot(xs, ys)

请参阅此处的zip文档:https://docs.python.org/3.5/library/functions.html#zip

相关问题 更多 >