python - 如何对绘图的 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. 或者,在绘制数据之前对数据进行排序?
解决方案
你可以使用 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)
推荐阅读
- java - 从 Apache Camel 中的 JSON 正文访问数据
- angular - 多次使用 enter 会增加代码的大小吗?
- function - Firebase 函数错误 - 错误:无法处理请求
- java - 为什么这段代码会打印出无限量的“你猜怎么着?”
- matlab - 我在机器学习中没有得到这行代码
- angular - RxJs 主题:获取发射器
- php - PHP从日历中的数据库添加事件
- java - 为什么我不能在 Spring-5.0.0.RELEASE 中导入 ApplicationContext
- centos7 - 在 Centos 7/RHEL 7 中安装最新版本
- java - Eclipse 代码格式:括号在编辑器上的缩进错误,但在设置中没问题