如果我有一个Python MatPlotLib图形(例如,一个matplotlib.axes._subplots.AxesSubplot对象),有没有办法从中提取点和误差线的位置? IE。我想要获取包含 x、y 坐标和 y 误差的数组。
示例:
import numpy as np
import seaborn as sb
x = np.random.uniform(-2, 2, 10000)
y = np.random.normal(x**2, np.abs(x) + 1)
p = sb.regplot(x=x, y=y, x_bins=10, fit_reg=None)
如何从点的“p”位置和误差线中提取?
感谢您的帮助!
最佳答案
误差条数据存储在p.lines
中,因为seaborn使用plt.plot
绘制它们。
您可以使用 line.get_xdata()
和 line.get_ydata()
访问他们的位置。
点数据存储在p.collections
中,因为它们是使用plt.scatter
在seaborn内部绘制的。
从 PathCollection
对象获取点位置需要一个额外的步骤,如以下答案所示:Get positions of points in PathCollection created by scatter():即您必须在访问之前先设置 offset_position
偏移量
。
这是一个从以下位置获取点数据和误差条数据的示例
matplotlib Axes
对象,p
。
import numpy as np
import seaborn as sb
import matplotlib.pyplot as plt
x = np.random.uniform(-2, 2, 10000)
y = np.random.normal(x**2, np.abs(x) + 1)
p = sb.regplot(x=x, y=y, x_bins=10, fit_reg=None)
# First, get the positions of the points:
coll = p.collections[0]
coll.set_offset_position('data')
points_xy = coll.get_offsets()
print points_xy
#[[-1.65295679 3.05723876]
# [-1.29981986 1.60258005]
# [-0.94417279 0.8999881 ]
# [-0.56964819 0.38035406]
# [-0.20253243 0.0774201 ]
# [ 0.15535504 0.024336 ]
# [ 0.5362322 0.30849082]
# [ 0.90482003 0.85788122]
# [ 1.26136841 1.66294418]
# [ 1.63048127 3.02934186]]
# Next, get the positions of the errorbars
xerr = []
yerr = []
for line in p.lines:
xerr.append(line.get_xdata()[0])
yerr.append(line.get_ydata().tolist())
print xerr
# [-1.6529567859649865, -1.2998198636006264, -0.94417278886439027, -0.56964818931133276, -0.20253243328132031, 0.15535504153419355, 0.53623219583456194, 0.90482002911787607, 1.2613684083224488, 1.6304812696399549]
print yerr
# [[2.908807029542707, 3.200571530218434], [1.4449980200239572, 1.751504207194087], [0.7633753040974505, 1.029774999216172], [0.26593411110949544, 0.4753543268237353], [-0.0030674495857816496, 0.15582564460187567], [-0.052610243112427575, 0.09899773706322114], [0.21019700161329888, 0.41120457637300634], [0.7328000635837721, 0.9826379405190817], [1.508513523393156, 1.8184617796582343], [2.885113765027557, 3.1670479251950376]]
plt.show()
这里 points_xy
是点的 (x,y)
坐标列表,xerr
是误差线的 x 坐标(当然,它与 Points_xy 中的 x 坐标相同),而 yerr 是 y 坐标对的列表:每个误差条的顶部和底部.
关于python - 从 Python MatPlotLib 图形中提取误差线和点位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46270643/