python - 从折线图中提取 (x,y) 值
问题描述
假设我有 2 组数据并且我使用 plt.plot 来绘制图表。
import matplotlib.pyplot as plt
import numpy as np
x=range(5,46,5)
y=[1.60,1.56,1.54,1.53,1.53,1.58,1.70,1.97,2.68]
plt.plot(x,y)
如何获取 plt.plot 创建的折线图的 x,y 值?
为清楚起见进行编辑:我想要做的是获取由 plt.plot 创建的线的坐标,而不是获取用于创建图形的数据。
编辑更清楚:我想在 pyplot 绘制的线中获取我的每个 (x,y) 对之间的点的坐标。
解决方案
Axes对象有一个属性transData
。此转换可用于将数据坐标转换为显示坐标:
x=range(5,46,5)
y=[1.60,1.56,1.54,1.53,1.53,1.58,1.70,1.97,2.68]
plt.gca().set_xlim(5,46)
plt.gca().set_ylim(1.5,3)
plt.plot(x,y)
print(plt.gca().transData.transform(list(zip(x,y))))
最后一行打印以显示坐标表示的数据点数组:
[[ 54. 50.496 ]
[ 94.82926829 44.6976 ]
[135.65853659 41.7984 ]
[176.48780488 40.3488 ]
[217.31707317 40.3488 ]
[258.14634146 47.5968 ]
[298.97560976 64.992 ]
[339.80487805 104.1312 ]
[380.63414634 207.0528 ]]
此输出意味着第一个数据点(5, 1.60)
显示在 处(54.0, 50.495)
,最后一个数据点(45, 2.69)
显示在 处(380.634, 207.052)
。
编辑:此列表中两个数据点之间的剩余点可以使用interp1d计算:
display_coords = plt.gca().transData.transform(list(zip(x,y)))
from scipy.interpolate import interp1d
f = interp1d(display_coords[:,0], display_coords[:,1])
display_x = np.linspace(min(display_coords[:,0]), max(display_coords[:,0]), num=100, endpoint=True)
list(zip(display_x, f(display_x)))
结果:
[(54.0, 50.49599999999998),
(57.29933481152993, 50.0274424242424),
(60.59866962305987, 49.55888484848483),
(63.8980044345898, 49.09032727272725),
(67.19733924611974, 48.62176969696967),
...
(367.43680709534374, 173.78521212121217),
(370.7361419068736, 182.102109090909),
(374.0354767184036, 190.41900606060602),
(377.3348115299335, 198.735903030303),
(380.63414634146346, 207.0528)]
实际值取决于显示、设置等,并且可能会有所不同。
推荐阅读
- python - 使用 pyelftools 抓取程序头信息
- json - Microsoft Bot Framework API 创建与多个成员的对话
- python - 传递默认参数的pythonic方式是什么?
- sql - 何时使用不存在的插入选择?
- c# - 循环内的异步操作 - 如何保持对执行的控制?
- python - 使用 Gorilla 包进行猴子修补,应用于超类方法
- java - 在电影院 java 中查找连续可用的免费座位
- java - 如何从在 Node.js 环境中运行的 Gulp 构建中调用 Gradle 构建任务
- generics - Rust 泛型迭代地构造元组
- python - 用pymap3d计算熊猫列的有效方法?