首页 > 解决方案 > 如何对绘图的 X ayis 中的数据点进行排序

问题描述

在此处输入图像描述我正在尝试从字典中绘制数据。每个字典值将在图中产生一行(值是列表的列表)

这些线有不同数量的点,因此 X ayis 点没有正确排序。

例如在上图中,点“3802814”是在点 3848766 和 3872755 之后的一条线上找到的,并绘制在右侧(未按我的意愿正确排序)。我知道字典不能这样排序,以克服这一点。

代码是:

# Dictionary: timing_of[clk_name]= {"clk1": [[Xlabel1, N1, M1, L1], [Xlabel2, N2, M2, L2]...]}
for clk_name, clk_data in timing_of.items(): 
   # Plot Xlabels with N-values in Y axis
   plt.plot([col[0] for col in clk_data] , [col[1] for col in clk_data], label=clk_name) 

plt.gca().legend(loc='center left', bbox_to_anchor=(1 , 0.8), prop={'size': 7}) 
plt.show() 

我该怎么做: 1. 在显示绘图之前对 X ayis 进行排序 2. 或者,在绘制数据之前对数据进行排序?

标签: pythonsortingmatplotlib

解决方案


你可以使用 numpy

import numpy as np
# Dictionary: timing_of[clk_name]= {"clk1": [[Xlabel1, N1, M1, L1], [Xlabel2, N2, M2, L2]...]}
# Dictionary: timing_of[clk_name]= {"clk1": [[Xlabel1, N1, M1, L1], [Xlabel2, N2, M2, L2]...]}
X_all = np.array([])
Y_all = np.array([])
for clk_name, clk_data in timing_of.items(): 
   X = np.array([col[0] for col in clk_data])
   Y = np.array([col[1] for col in clk_data])
   argsort = np.argsort(X)
   X = X[argsort]
   Y = Y[argsort]
   # search the indexes to append in the right place
   appendIndex  = np.searchsorted(X_all, X)
   X_all = np.insert(X_all , appendIndex, X)
   Y_all = np.insert(Y_all , appendIndex, Y)

plt.plot(X_all , Y_all) 

推荐阅读