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

Gre*_*reg 22 python matplotlib

到目前为止我有这个:

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")
Run Code Online (Sandbox Code Playgroud)

这创造了: 在此输入图像描述

我想要做的就是伸展它以使Z轴高9倍并保持X和Y相同.我想保持相同的坐标.

到目前为止我试过这个家伙:

fig = plt.figure(figsize=(4.,35.))
Run Code Online (Sandbox Code Playgroud)

但这只是延伸了plot.png图像.

Chr*_*een 22

下面的代码示例提供了一种相对于其他轴缩放每个轴的方法.但是,要这样做,您需要修改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()
Run Code Online (Sandbox Code Playgroud)

标准输出:

正常比例

按(1,2,3)缩放:

Scale_x = 1,Scale_y = 2,Scale_z = 3

按(1,1,3)缩放:

Scale_x = 1,Scale_y = 1,Scale_z = 3

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

交换z和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()
Run Code Online (Sandbox Code Playgroud)


And*_*bis 16

请注意,下面的答案简化了补丁,但使用与@ChristianSarofeen的答案相同的基本原则.

正如其他答案中已经指出的那样,它不是当前在matplotlib中实现的功能.但是,由于您要求的只是一个3D变换,可以应用于matplotlib使用的现有投影矩阵,并且由于Python的精彩功能,这个问题可以通过一个简单的oneliner来解决:

ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([scale_x, scale_y, scale_z, 1]))
Run Code Online (Sandbox Code Playgroud)

其中scale_x,scale_yscale_z是的值从0到1,将相应地重新缩放沿每个轴的曲线图.ax只是可以获得的3D轴ax = fig.gca(projection='3d')

说明

为了解释,该函数get_projAxes3D生成从当前视听位置的投影矩阵.将其乘以缩放矩阵:

scale_x, 0,       0
0,       scale_y, 0
0,       0,       scale_z
0,       0,       1
Run Code Online (Sandbox Code Playgroud)

包括缩放到渲染器使用的投影中.所以,我们在这里做的是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()
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

在此输入图像描述


ero*_*3pi 16

就我而言,我想将 z 轴拉伸 2 倍以获得更好的点可见性

from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt
# plt.rcParams["figure.figsize"] = (10,200)
# plt.rcParams["figure.autolayout"] = True
ax = plt.axes(projection='3d')
ax.set_box_aspect(aspect = (1,1,2))

ax.plot(dataX,dataY,dataZ)
Run Code Online (Sandbox Code Playgroud)

  • 我相信这是最好的现代答案,显然现在你不需要其他任何东西,这就像一个魅力! (5认同)

tmd*_*son 5

我看起来默认情况下,mplot3d会在很高的情节的顶部和底部留下相当多的空间.但是,您可以使用它来欺骗它fig.subplots_adjust,并将顶部和底部扩展到正常的绘图区域(即top > 1bottom < 0).您的特定情节可能需要一些试验和错误.

我为x,y和z创建了一些随机数组,其限制类似于你的情节,并且发现下面的参数(bottom=-0.15,top = 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")
Run Code Online (Sandbox Code Playgroud)