【问题标题】:matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot?matplotlib (mplot3d) - 如何在 3D 图中增加轴的大小(拉伸)?
【发布时间】:2015-07-25 05:35:29
【问题描述】:

到目前为止我有这个:

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")

创建:

我想做的是将其拉伸以使 Z 轴高 9 倍并保持 X 和 Y 相同。不过我想保持相同的坐标。

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

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

但这只是拉长了 plot.png 图像。

【问题讨论】:

  • 你试过set_zlim(z_min, z_max)吗?还是set_zlim3d?
  • 感谢您的建议。兹利姆是做什么的?我不确定我会为 z_min 和 z_max 放什么。我对它的 z 边界很满意,我只是希望它被拉伸。
  • 我误会了。看起来您想更改 3d 纵横比。这样做取决于您正在使用的 matplotlib 版本。试试看here1 或here2
  • 谢谢。我想我不明白 here1 链接会做什么。似乎它不会设置纵横比。我在问这个问题之前阅读了here2,但我看不到如何将答案应用于我的代码。
  • 有一个解决方案。一个非常简单的猴子补丁,只需要在代码中添加一行。在下面查看我的答案:stackoverflow.com/a/30419243/1576602

标签: python matplotlib


【解决方案1】:

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

标准输出:

按 (1, 2, 3) 缩放:

按 (1, 1, 3) 缩放:

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

以下是代码的较短版本。

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()

【讨论】:

  • @gboffi 我可以。您应该能够简单地复制代码并运行它。
  • 哈哈,也打败我吧。我认为这是这样做的方法。您可以查看默认缩放,world_transformation(),here
  • 一个限制是它要求数据居中。否则,点积还将创建图形的空间变换,可能会将其移出屏幕
  • 我发现使用此解决方案的结果图总是如此缩小。
【解决方案2】:

请注意,下面的答案简化了补丁,但使用的基本原理与@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]))

其中scale_x、scale_y 和scale_z 是从 0 到 1 的值,它们将相应地沿每个轴重新缩放您的绘图。 ax 就是简单的 3D 轴,可以用 ax = fig.gca(projection='3d') 获得

说明

解释一下,Axes3D的函数get_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,我们得到:

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

【讨论】:

    【解决方案3】:

    我看起来默认情况下,mplot3d 会在一个非常高的地块的顶部和底部留下相当多的空间。但是,您可以欺骗它使用fig.subplots_adjust 填充该空间,并将顶部和底部延伸到正常绘图区域之外(即top > 1 和bottom < 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")
    

    【讨论】:

    • 我不喜欢这个选项,因为你真的只是在扭曲视口。当您尝试旋转此图时,您可以知道图像实际上只是偏斜了。
    【解决方案4】:

    我在搜索类似问题时发现了这一点。经过一番试验,也许我可以在这里分享一些我的初步发现。matplotlib 库是巨大的! (我是新人)。请注意,与这个问题非常相似,我想要的只是在不扭曲图表的情况下“直观地”拉伸图表。

    背景故事(只显示关键代码 sn-ps 以避免对了解该库的人造成不必要的混乱,如果您想要可运行的代码,请发表评论): 我有三个分别代表 X、Y 和 Z 数据点的 1-d ndarray。显然我不能使用 plot_surface(因为它需要 2d ndarrays 用于每个暗淡)所以我选择了非常有用的 plot_trisurf:

    fig = plt.figure()
    ax = Axes3D(fig)
    3d_surf_obj = ax.plot_trisurf(X, Y, Z_defl, cmap=cm.jet,linewidth=0,antialiased=True)
    

    你可以把这个情节想象成一艘在波浪中变形的漂浮驳船......正如你所看到的,轴的拉伸使它在视觉上非常具有欺骗性(注意 x 应该是 x6 倍于 y 和 >>> >> z)。虽然情节点是正确的,但我至少想要一些视觉上更“拉伸”的东西。如果可以的话,正在寻找快速修复。长话短说,我发现...'figure.figsize'一般设置有点成功(见下面的sn-p)。

        matplotlib.rcParams.update({'font.serif': 'Times New Roman',
                                    'font.size': 10.0,
                                    'axes.labelsize': 'Medium',
                                    'axes.labelweight': 'normal',
                                    'axes.linewidth': 0.8,
                                     ###########################################
                                     # THIS IS THE IMPORTANT ONE FOR STRETCHING
                                     # default is [6,4] but...i changed it to
                                    'figure.figsize':[15,5]   # THIS ONE #
                                  })
    

    对于 [15,5],我得到了类似...

    相当整洁!!

    所以我开始推动它....并在决定在那里定居之前起床到 [20,6]..

    如果您想尝试在视觉上拉伸垂直轴,请尝试使用... [7,10] 之类的比率,在这种情况下给我...

    不要太破旧!

    应该这样做是为了提高视觉能力。

    【讨论】:

      【解决方案5】:

      听起来您正在尝试调整情节的规模。我认为没有办法将 linear 比例拉伸到用户规格,但您可以使用 set_yscale()、set_xscale()、set_zscale() 来改变彼此之间的比例。

      直观地说,set_yscale(log)、set_xscale(log)、set_zscale(linear) 可能会解决您的问题。

      一个可能更好的选择:指定一个拉伸,将它们全部设置为具有相同日志基数的 symlog,然后使用 linscalex/linscaley kwargs 根据您的规范指定 Z 轴的 symlog 比例。

      更多:

      http://matplotlib.org/mpl_toolkits/mplot3d/api.html

      【讨论】:

        【解决方案6】:

        在我的例子中,我想将 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)
        

        【讨论】:

          【解决方案7】:

          将所有 z 值乘以 9,

          ax.scatter(x, y, 9*z, zdir='z', c= 'red')
          

          然后给z轴自定义绘图标签和间距。

          ax.ZTick = [0,-9*50, -9*100, -9*150, -9*200];
          ax.ZTickLabel = {'0','-50','-100','-150','-200'};
          

          【讨论】:

          • 这不会使 Z 轴变高。
          猜你喜欢
          • 2014-08-11
          • 1970-01-01
          • 1970-01-01
          • 2013-02-04
          • 1970-01-01
          • 2020-05-28
          • 1970-01-01
          • 1970-01-01
          • 2015-10-15
          相关资源
          最近更新 更多