Python 的 Matplotlib 以错误的顺序绘图 [英] Python's Matplotlib plotting in wrong order

查看:27
本文介绍了Python 的 Matplotlib 以错误的顺序绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

plt.semilogy(out_samp,error_mc)

我明白了

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

先谢谢你!

解决方案

在绘图前按 x 轴的值排序.这是一个 MWE.

import itertoolsx = [3, 5, 6, 1, 2]y = [6, 7, 8, 9, 10]列表 = 排序(itertools.izip(*[x, y]))new_x, new_y = list(itertools.izip(*lists))# 导入操作符# new_x = map(operator.itemgetter(0), 列表) # [1, 2, 3, 5, 6]# new_y = map(operator.itemgetter(1), 列表) # [9, 10, 6, 7, 8]# 阴谋导入 matplotlib.pylab 作为 pltplt.plot(new_x, new_y)plt.show()

对于小数据,

Basically I have two arrays, one containing the values of the x-axis and the second containing the values of the y-axis. The problem is, when I do

plt.semilogy(out_samp,error_mc)

I get this

Which doesn't make any sense. That is because the plot functions plots everything as it encounters in the x array, not caring whether it's sorted in ascending order or not. How can I sort these two arrays so that the x array is sorted by increasing value and the y axis sorted in the same way so that the points are the same but the plot is connected so that it doesn't make this mess?

Thank you in advance!

解决方案

Sort by the value of x-axis before plotting. Here is an 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()

For small data, zip (as mentioned by other answerers) is enough.

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


The result,

这篇关于Python 的 Matplotlib 以错误的顺序绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆