如何使用 matplotlib 将 3d 数据单位转换为显示单位? [英] How to transform 3d data units to display units with matplotlib?

查看:35
本文介绍了如何使用 matplotlib 将 3d 数据单位转换为显示单位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能有点疯狂,但我正在尝试使用 matplotlib v1.1.0 创建 3d 散点图的可点击图像地图.我已经阅读了如何为 2d 绘图执行此操作(参见 这个博客),但3d让我感到困惑.基本问题是我不知道如何获取 3d 轴的显示坐标.

This may be a bit crazy, but I'm trying to create a clickable image map of a 3d scatter plot using matplotlib v1.1.0. I've read how to do it for 2d plots (c.f. this blog), but 3d has mystified me. The basic problem is I don't know how to get the display coordinates for a 3d axes.

在二维情况下,为了让点击点正确定位在散点上,您需要将每个散点从数据单位转换为显示单位.使用 ax.transData 似乎相当简单.我希望这也适用于 3d 轴,但似乎不是.例如,这是我尝试做的:

In the 2d case, in order to get the click points correctly located over the scatter points, you need to convert each scatter point from data units to display units. That seems fairly straight forward using ax.transData. I was hoping this would also work for 3d axes, but it appears not. For example, here's what I have tried to do:

# create the plot
from mpl_toolkits.mplot3d import Axes3D
fig = pylab.figure()
ax = fig.add_subplot(111, projection = '3d')
x = y = z = [1, 2, 3]
sc = ax.scatter(x,y,z)
# now try to get the display coordinates of the first point
sc.axes.transData.transform((1,1,1))

然而,最后一行给了我一个无效的顶点数组"错误.它仅在您将两个点的元组传递给它时才有效,例如 (1,1),但这对于 3d 绘图没有意义.某处一定有一种方法可以将 3d 投影转换为 2d 显示坐标,但是在破坏互联网几个小时后我找不到它.有谁知道如何正确地做到这一点?

The last line gives me an "Invalid vertices array" error, however. It only works if you pass it a tuple of two points, e.g., (1,1), but that doesn't make sense for a 3d plot. There must be a method somewhere that converts the 3d projection to 2d display coordinates, but after wracking the internet for a couple hours I can't find it. Does anyone know how to correctly do this?

推荐答案

您可以使用 proj3d.proj_transform() 将 3D 坐标投影到 2D.调用 ax.get_proj() 获取变换矩阵:

You can use proj3d.proj_transform() to project 3D coordinate to 2D. call ax.get_proj() to get the transform matrix:

import pylab
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import proj3d
fig = pylab.figure()
ax = fig.add_subplot(111, projection = '3d')
x = y = z = [1, 2, 3]
sc = ax.scatter(x,y,z)

#####################    
x2, y2, _ = proj3d.proj_transform(1, 1, 1, ax.get_proj())
print x2, y2   # project 3d data space to 2d data space
print ax.transData.transform((x2, y2))  # convert 2d space to screen space
#####################
def on_motion(e):
    # move your mouse to (1,1,1), and e.xdata, e.ydata will be the same as x2, y2
    print e.x, e.y, e.xdata, e.ydata  
fig.canvas.mpl_connect('motion_notify_event', on_motion)
pylab.show()

这篇关于如何使用 matplotlib 将 3d 数据单位转换为显示单位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆