Python 3.5绘制3D曲面图遇ValueError:Z需为二维数组的解决方法
Hey Denis, let's sort out that ValueError: Argument Z must be 2-dimensional issue you're hitting when trying to plot your 3D surface. Here's what's going wrong and how to fix it:
Why the Error Happens
The plot_surface function from Matplotlib expects a 2-dimensional array for the Z parameter. This is because a surface plot needs to map every combination of your A and C parameters to an area value—think of it as a grid where each cell is the area for a specific A-C pair. Your current result_area is a 1D array, which only holds area values for paired indices (like A[0] with C[0], A[1] with C[1], etc.), not all possible combinations.
Step-by-Step Solution
1. Generate Grid Data for Parameters
First, we need to create a 2D grid of all possible A and C combinations using np.meshgrid. This converts your 1D parameter arrays into 2D matrices where each point represents a unique A-C pair.
2. Calculate Area for Every Grid Point
Next, we'll loop through each point in the grid, call your get_area function to compute the area for that A-C pair, and store these values in a 2D Z array.
3. Plot the Surface
Finally, we'll use the 2D grid matrices (X, Y) and the corresponding 2D area array (Z) to generate the surface plot, just like the example you referenced.
Full Working Code
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Your original parameter arrays a = [70, 71,72,73,74,75,76,77,78,79,80,81,82,82,83,84,85,86,87,88,89] c = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Convert to numpy arrays for easier manipulation a_np = np.array(a) c_np = np.array(c) # Create 2D grids for A (X) and C (Y) X, Y = np.meshgrid(a_np, c_np) # Initialize a 2D array to store all area values Z = np.zeros_like(X) # Calculate area for every A-C combination for i in range(X.shape[0]): for j in range(X.shape[1]): Z[i, j] = get_area(X[i, j], Y[i, j]) # Create the 3D plot fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') # Plot the surface with a color map for better visualization surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none') # Add a color bar to show area values corresponding to colors fig.colorbar(surf, shrink=0.5, aspect=5) # Label your axes for clarity ax.set_xlabel('Parameter A') ax.set_ylabel('Parameter C') ax.set_zlabel('Surface Area') ax.set_title('Area Variation with Parameters A and C') plt.show()
Key Notes
- Your original
aarray has 21 elements andchas 20, so the resultingX,Y, andZmatrices will be 20 rows × 21 columns—this matches all possible combinations of your parameters. - Using
rstride=1andcstride=1ensures the surface is smooth (you can adjust these if you want fewer grid lines). - The
viridiscolormap makes it easier to visualize how area changes across parameters, and the color bar helps interpret the values.
内容的提问来源于stack exchange,提问作者Denis

