从matplotlib中的3D散点图中提取数据 [英] Extracting data from a 3D scatter plot in matplotlib
问题描述
我正在编写一个用于在 matplotlib 中制作 3D 散点图的界面,我想从 python 脚本访问数据.对于二维散点图,我知道过程将是:
I'm writing an interface for making 3D scatter plots in matplotlib, and I'd like to access the data from a python script. For a 2D scatter plot, I know the process would be:
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
h = ax.scatter(x,y,c=c,s=15,vmin=0,vmax=1,cmap='hot')
data = h.get_offsets()
有了上面的代码,我知道数据将是一个(N,2)
numpy数组,其中填充了我的(x,y)
数据.当我尝试对 3D 数据执行相同的操作时:
With the above code, I know that data would be a (N,2)
numpy array populated with my (x,y)
data. When I try to perform the same operation for 3D data:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
h = ax.scatter(x,y,z,c=c,s=15,cmap='hot',vmin=0,vmax=1)
data = h.get_offsets()
结果 data
变量仍然是 (N,2)
numpy 数组,而不是 (N,3)
numpy 数组. data
的内容不再匹配我的任何输入数据;我以为 data
用我的3D数据的2D投影填充,但是我真的很想访问用于生成散点图的3D数据.这可能吗?
The resulting data
variable is still an (N,2)
numpy array rather than a (N,3)
numpy array. The contents of data
no longer match any of my input data; I assume that data
is populated with the 2D projections of my 3D data, but I would really like to access the 3D data used to generate the scatter plot. Is this possible?
推荐答案
确实,通过get_offsets
得到的坐标就是投影坐标.原始坐标隐藏在 mpl_toolkits.mplot3d.art3d.Path3DCollection
中,由 scatter
在三维轴上返回.您将从 ._offsets3d
属性获取原始坐标.(这是一个私有"属性,但不幸的是检索此信息的唯一方法.)
Indeed, the coordinates obtained via get_offsets
are the projected coordinates.
The original coordinates are hidden inside the mpl_toolkits.mplot3d.art3d.Path3DCollection
which is returned by the scatter
in three dimensional axes. You would obtain the original coordinates from the ._offsets3d
attribute. (This is a "private" attribute, but unfortunately the only way to retrieve this information.)
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
x = [1,2,3,4]
y = [1,3,3,5]
z = [10,20,30,40]
c= [1,2,3,1]
scatter = ax.scatter(x,y,z,c=c,s=15,cmap='hot',vmin=0,vmax=1)
data = np.array(scatter._offsets3d).T
print(scatter) # prints mpl_toolkits.mplot3d.art3d.Path3DCollection
print(data)
# prints
#
# [[ 1. 1. 10.]
# [ 2. 3. 20.]
# [ 3. 3. 30.]
# [ 4. 5. 40.]]
这篇关于从matplotlib中的3D散点图中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!