与未排序的数据相交的matplotlib图 [英] Intersecting matplotlib graph with unsorted data
问题描述
使用matplotlib
绘制一些点时,在创建图形时遇到一些奇怪的行为.这是生成该图的代码.
When plotting some points with matplotlib
I encountered some strange behavior when creating a graph. Here is the code to produce this graph.
import matplotlib.pyplot as plt
desc_x =[4000,3000,2000,2500,2750,2250,2300,2400,2450,2350]
rmse_desc = [.31703 , .31701, .31707, .31700, .31713, .31698, .31697, .31688, .31697, .31699]
fig = plt.figure()
ax = plt.subplot(111)
fig.suptitle('title')
plt.xlabel('x')
plt.ylabel('y')
ax.plot(desc_x, rmse_desc, 'b', label='desc' )
ax.legend()
plt.show()
这是它创建的图形
您可以看到,此图具有相交的线,有些在线图中看不到.当我隔离点并且不画线时,我得到以下结果:
As you can tell, this graph has intersecting lines, something one doesn't see in a line graph. When I isolate the points, and don't draw the lines, I get this result:
您可以说,有一种无需交叉线即可连接这些点的方法.
As you can tell, there is a way to connect these points without intersecting lines.
为什么matplotlib会这样做?我想我可以通过不对我的xcolumn不排序来解决它,但是如果我对它进行排序,我将失去从x1到y1的映射.
Why does matplotlib do this? I think I could fix it by not having my xcolumn be unsorted, but if I sort it, I will lose the mapping from x1 to y1.
推荐答案
You can maintain the order using numpy's argsort
function.
Argsort"...沿着给定的轴按排序顺序返回与该索引数据形状相同的索引数组.",因此我们可以使用它来对x和y坐标重新排序.这是完成的方式:
Argsort "...returns an array of indices of the same shape as a that index data along the given axis in sorted order.", so we can use this to re-order the x and y coordinates together. Here's how it's done:
import matplotlib.pyplot as plt
import numpy as np
desc_x =[4000,3000,2000,2500,2750,2250,2300,2400,2450,2350]
rmse_desc = [.31703 , .31701, .31707, .31700, .31713, .31698, .31697, .31688, .31697, .31699]
order = np.argsort(desc_x)
xs = np.array(desc_x)[order]
ys = np.array(rmse_desc)[order]
fig = plt.figure()
ax = plt.subplot(111)
fig.suptitle('title')
plt.xlabel('x')
plt.ylabel('y')
ax.plot(xs, ys, 'b', label='desc' )
ax.legend()
plt.show()
这篇关于与未排序的数据相交的matplotlib图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!