matplotlib 使用plot_surface缩放3D曲面图的垂直(z)轴

wljmcqd8  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(148)

如何在matplotlib中缩放曲面图的Z轴?以下面的数据集和图为例。

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
x, y = np.meshgrid(x, y)
# Generate a 3D surface 
z = np.exp(-0.1*x**2 - 0.1*y**2)

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d')
# Create the surface plot
surf = ax.plot_surface(x, y, z, cmap='plasma')
plt.show()

我想缩放它,使它看起来像下面的图(我已经通过调整轴限制完成了),但z轴限制仍然在0和1之间。这可能吗?我在文档中找不到任何关于如何做到这一点的内容。为了说明,R中的persp函数有expand参数,它正好可以做我想做的事情。

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d')
# Create the surface plot
surf = ax.plot_surface(x, y, z, cmap='plasma')
ax.set_zlim([0, 2.5])
plt.show()

更新

为了澄清,这里有一个例子,我正在尝试使用R代码做什么。我正在尝试调整z轴的长宽比。在R中使用persp函数,我们可以使用`expand参数来完成这一点。例如:

# Generate synthetic data for demonstration purposes
x <- seq(-5, 5, length.out = 50)
y <- seq(-5, 5, length.out = 50)
z <- matrix(0, length(x), length(y))

# Generate a Gaussian surface
for(i in 1:length(x)) {
  for(j in 1:length(y)) {
    z[i, j] <- exp(-0.1 * x[i]^2 - 0.1 * y[j]^2)
  }
}

nrz <- nrow(z)
ncz <- ncol(z)
# Create a function interpolating colors in the range of specified colors
jet.colors <- colorRampPalette(c("#0d0887", "#cc4678", "#f0f921"))
# Generate the desired number of colors from this palette
nbcol <- 100
color <- jet.colors(nbcol)
# Compute the z-value at the facet centres
zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]
# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)

expand = 1.0

persp(x, y, z, theta = 45, phi = 30, expand = 1.0, col = color[facetcol])

expand = 0.3

persp(x, y, z, theta = 45, phi = 30, expand = 0.3, col = color[facetcol])

y1aodyip

y1aodyip1#

听起来你想改变3D图的长宽比。按照你的R示例,你可以在matplotlib中使用ax.set_box_aspect函数将长宽比改变为0.3。该函数接受一个提供XYZ比率的元组。

ax.set_box_aspect((1,1,0.3))

llmtgqce

llmtgqce2#

你必须计算z缩放并放入你的图中。下面是示例:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
x, y = np.meshgrid(x, y)

# Generate a 3D surface
z = np.exp(-0.1*x**2 - 0.1*y**2)

# Find the maximum value in the original "z" values
max_z = z.max()

# Calculate the scaling factor to make the max_z equal to 1
scaling_factor = 1 / max_z
 
# Scale the "z" values
z_scaled = z * scaling_factor

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')

# Create the surface plot with the scaled z-values
surf = ax.plot_surface(x, y, z_scaled, cmap='plasma')

# Set Z-axis limits between 0 and 1
ax.set_zlim([0, 1])

plt.show()

下面是示例结果:

相关问题