首页 > 解决方案 > 从折线图中提取 (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) 对之间的点的坐标。

标签: pythonmatplotlibgraph

解决方案


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)]

实际值取决于显示、设置等,并且可能会有所不同。


推荐阅读