如何创建28°-34°坡度倾角矩阵并实现Python可视化绘图?
Hey there! Let's walk through how to build that slope angle matrix and visualize it with Python—super straightforward once you break it down. I'll cover both a smooth gradient matrix (for gradual transitions) and a random distribution (for real-world scattered slopes), plus a clean visualization using matplotlib.
Step 1: Generate the Slope Angle Matrix
We'll use numpy to handle matrix creation efficiently. Pick the option that fits your use case:
Option 1: Gradient Matrix (Smooth Transition)
This creates a matrix where angles transition evenly from 28° (top-left) to 34° (bottom-right). Adjust the matrix size to whatever you need!
import numpy as np # Define your angle bounds min_angle = 28 max_angle = 34 # Set matrix dimensions (e.g., 20x20—tweak this to your needs) matrix_shape = (20, 20) # Generate a linear range of angles and reshape into the matrix slope_matrix = np.linspace(min_angle, max_angle, num=matrix_shape[0]*matrix_shape[1]).reshape(matrix_shape)
Option 2: Random Distribution Matrix
If you want angles scattered randomly within the 28-34° range (great for simulating natural terrain), use this instead:
# Create a matrix with random angles between 28° and 34° slope_matrix = np.random.uniform(low=min_angle, high=max_angle, size=matrix_shape)
Step 2: Visualize the Matrix
We'll use matplotlib to plot the matrix as a heatmap—this makes it easy to see exactly where each slope angle falls. Here's the full visualization code:
import matplotlib.pyplot as plt # Set up the plot window plt.figure(figsize=(8, 6)) # Plot the matrix as a heatmap (use 'viridis' for a colorblind-friendly scheme) im = plt.imshow(slope_matrix, cmap='viridis', vmin=min_angle, vmax=max_angle) # Add clear labels and a title plt.title('Slope Angle Distribution (28° to 34°)', fontsize=14, pad=15) plt.xlabel('Column Position', fontsize=12) plt.ylabel('Row Position', fontsize=12) # Add a color bar that directly maps colors to angles color_bar = plt.colorbar(im) color_bar.set_label('Slope Angle (°)', fontsize=12) # Optional: Add faint grid lines to make individual matrix cells easier to spot plt.grid(visible=True, linestyle='--', alpha=0.5, color='white') # Display the plot plt.show()
Quick Tweaks You Might Want
- Resize the matrix: Change
matrix_shapeto(50,50)for a denser grid or(10,10)for something simpler. - Change the color scheme: Swap
'viridis'for'plasma','inferno', or'coolwarm'to get a different look. - Reverse the gradient: Flip
min_angleandmax_angleinnp.linspace()to make the highest angles start at the top-left.
内容的提问来源于stack exchange,提问作者Steren

