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

查看:80
本文介绍了如何使用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.

在2d情况下,为了使点击点正确位于散点,您需要将每个散点从数据单位转换为显示单位。使用 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天全站免登陆