matplotlib(mplot3d)-如何在3D打印中增加轴(拉伸)的大小?

2024-04-26 23:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

到目前为止我有这个:

x,y,z = data.nonzero()    
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, zdir='z', c= 'red')
plt.savefig("plot.png")

它创造了: enter image description here

我想做的是拉伸它,使Z轴高出9倍,并保持X和Y相同。不过,我想保持同样的坐标。

到目前为止我试过这个人:

fig = plt.figure(figsize=(4.,35.))

但这只是扩展了plot.png图像。


Tags: adddataplotpngfigpltredax
3条回答

下面的代码示例提供了一种相对于其他轴缩放每个轴的方法。但是,要执行此操作,您需要修改Axes3D.get_proj函数。下面是一个基于matplot lib提供的示例的示例:http://matplotlib.org/1.4.0/mpl_toolkits/mplot3d/tutorial.html#line-plots

(这个答案后面有一个简短的版本)

from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import proj3d

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt

#Make sure these are floating point values:                                                                                                                                                                                              
scale_x = 1.0
scale_y = 2.0
scale_z = 3.0

#Axes are scaled down to fit in scene                                                                                                                                                                                                    
max_scale=max(scale_x, scale_y, scale_z)

scale_x=scale_x/max_scale
scale_y=scale_y/max_scale
scale_z=scale_z/max_scale

#Create scaling matrix                                                                                                                                                                                                                   
scale = np.array([[scale_x,0,0,0],
                  [0,scale_y,0,0],
                  [0,0,scale_z,0],
                  [0,0,0,1]])
print scale

def get_proj_scale(self):
    """                                                                                                                                                                                                                                    
    Create the projection matrix from the current viewing position.                                                                                                                                                                        

    elev stores the elevation angle in the z plane                                                                                                                                                                                         
    azim stores the azimuth angle in the x,y plane                                                                                                                                                                                         

    dist is the distance of the eye viewing point from the object                                                                                                                                                                          
    point.                                                                                                                                                                                                                                 

    """
    relev, razim = np.pi * self.elev/180, np.pi * self.azim/180

    xmin, xmax = self.get_xlim3d()
    ymin, ymax = self.get_ylim3d()
    zmin, zmax = self.get_zlim3d()

    # transform to uniform world coordinates 0-1.0,0-1.0,0-1.0                                                                                                                                                                             
    worldM = proj3d.world_transformation(
        xmin, xmax,
        ymin, ymax,
        zmin, zmax)

    # look into the middle of the new coordinates                                                                                                                                                                                          
    R = np.array([0.5, 0.5, 0.5])

    xp = R[0] + np.cos(razim) * np.cos(relev) * self.dist
    yp = R[1] + np.sin(razim) * np.cos(relev) * self.dist
    zp = R[2] + np.sin(relev) * self.dist
    E = np.array((xp, yp, zp))

    self.eye = E
    self.vvec = R - E
    self.vvec = self.vvec / proj3d.mod(self.vvec)

    if abs(relev) > np.pi/2:
    # upside down                                                                                                                                                                                                                          
      V = np.array((0, 0, -1))
    else:
      V = np.array((0, 0, 1))
    zfront, zback = -self.dist, self.dist

    viewM = proj3d.view_transformation(E, R, V)
    perspM = proj3d.persp_transformation(zfront, zback)
    M0 = np.dot(viewM, worldM)
    M = np.dot(perspM, M0)

    return np.dot(M, scale);

Axes3D.get_proj=get_proj_scale

"""
You need to include all the code above.
From here on you should be able to plot as usual.
"""

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure(figsize=(5,5))
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()

plt.show()

标准输出:

Normal Scale

按(1,2,3)缩放:

Scale_x=1, Scale_y=2, Scale_z=3

按(1,1,3)缩放:

Scale_x=1, Scale_y=1, Scale_z=3

我特别喜欢这种方法的原因是, 交换z和x,按(3,1,1)缩放:

Swap z and x, scale_x=4

下面是代码的简短版本。

from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import proj3d

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure(figsize=(5,5))
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)


"""                                                                                                                                                    
Scaling is done from here...                                                                                                                           
"""
x_scale=1
y_scale=1
z_scale=2

scale=np.diag([x_scale, y_scale, z_scale, 1.0])
scale=scale*(1.0/scale.max())
scale[3,3]=1.0

def short_proj():
  return np.dot(Axes3D.get_proj(ax), scale)

ax.get_proj=short_proj
"""                                                                                                                                                    
to here                                                                                                                                                
"""

ax.plot(z, y, x, label='parametric curve')
ax.legend()

plt.show()

请注意,下面的答案简化了修补程序,但使用的基本原理与@ChristianSarofeen的答案相同。

溶液

正如其他答案中已经指出的,它不是当前在matplotlib中实现的特性。但是,由于您所请求的只是一个可以应用于matplotlib所使用的现有投影矩阵的3D转换,并且由于Python的出色特性,这个问题可以用一个简单的oneliner解决:

ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([scale_x, scale_y, scale_z, 1]))

其中scale_xscale_yscale_z是从0到1的值,它们将相应地沿每个轴重新缩放绘图。ax只是可以通过ax = fig.gca(projection='3d')获得的3D轴

解释

为了解释,函数Axes3Dget_proj从当前观看位置生成投影矩阵。乘以缩放矩阵:

scale_x, 0,       0
0,       scale_y, 0
0,       0,       scale_z
0,       0,       1

包括渲染器使用的投影的缩放。所以,我们现在要做的是用一个表达式替换原来的get_proj函数,这个表达式取原来get_proj的结果,然后乘以缩放矩阵。

示例

用标准参数函数示例说明结果:

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

# OUR ONE LINER ADDED HERE:
ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([0.5, 0.5, 1, 1]))

ax.plot(x, y, z)
plt.show()

对于值0.5, 0.5, 1,我们得到:

enter image description here

而对于值0.2, 1.0, 0.2,我们得到:

enter image description here

我看起来默认情况下,mplot3d会在一个非常高的地块的顶部和底部留下相当大的空间。但是,您可以使用fig.subplots_adjust技巧来填充该空间,并将顶部和底部扩展到正常绘图区域之外(即top > 1bottom < 0)。对于你的特殊情节,这里可能需要一些尝试和错误。

我为x、y和z创建了一些随机数组,其限制与您的图类似,并且发现下面的参数(bottom=-0.15top = 1.2)似乎工作正常。

您可能还需要更改ax.view_init以设置一个良好的视角。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from numpy import random

# Make some random data with similar limits to the OP's example
x,y,z=random.rand(3,100)
z*=250
y*=800
y+=900
x*=350
x+=1200

fig=plt.figure(figsize=(4,35))

# Set the bottom and top outside the actual figure limits, 
# to stretch the 3D axis
fig.subplots_adjust(bottom=-0.15,top=1.2)

ax = fig.add_subplot(111, projection='3d')

# Change the viewing angle to an agreeable one
ax.view_init(2,None)

ax.scatter(x, y, z, zdir='z', c= 'red')
plt.savefig("plot.png")

相关问题 更多 >