Python的Matplotlib打印顺序错误

2024-05-14 20:21:40 发布

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

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

plt.semilogy(out_samp,error_mc)

我明白了

enter image description here

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

提前谢谢你


Tags: 函数内容排序plot方式plterror数组
3条回答

对这两个数据列表进行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

打印前按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

对列表进行排序的另一种方法是使用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)

注意,上面的代码使用sort()两次:首先使用np.sort(x),然后使用f[np.argsort(x)]。总的sort()调用可以减少到一个:

# once you have your x and f...
indices = np.argsort(x)
plt.plot(x[indices], f[indices], '-bo', ms = 2)

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

输出2

enter image description here

相关问题 更多 >

    热门问题