绘制函数密度图时遭遇TypeError: Invalid dimensions for image data错误
Hey there, let's walk through fixing your code step by step—those errors are totally fixable once we spot the root issues:
1. The Core Problem: 1D Data Won't Work with imshow
plt.imshow() expects 2D image data (like an M×N array representing a grid of values), but right now your r1 is a 1D array. Here's why:
xandyare both 1D arrays created withlinspace(shape:(1000,)each)- When you calculate
r1 = sqrt((x**2)+(y*2)), you're doing element-wise operations on two 1D arrays, which gives another 1D array.
To fix this, convert your 1D x/y arrays into a 2D grid using np.meshgrid():
x = linspace(0, D, 1000) y = linspace(0, D, 1000) X, Y = np.meshgrid(x, y) # This creates 2D coordinate matrices
2. Your Function Isn't Being Used (And Needs a Tweak)
You defined function1() but never assigned its output to a variable to plot. Also, relying on global variables isn't great practice—let's adjust the function to accept a parameter instead:
def function1(r): return sin(r)
3. Extent Mismatch Causes Wrong Axis Ranges
Your extent=[0,10,0,5] doesn't match your actual data range (x and y go from 0 to D=50). This is why your axes show 0.0 to 1.0—imshow falls back to using array indices when the extent doesn't align with the data. Update the extent to match your data, or let matplotlib auto-set it.
Fixed Full Code
import numpy as np import matplotlib.pyplot as plt from numpy import sin, cos, sqrt, arctan2 from pylab import plot, show, xlabel, ylabel, linspace, ylim D = 50 x = linspace(0, D, 1000) y = linspace(0, D, 1000) X, Y = np.meshgrid(x, y) # Convert to 2D grid # Note: I assumed `y*2` was a typo for Y²—if it's intentional, change back to X**2 + Y*2 r1 = sqrt(X**2 + Y**2) def function1(r): return sin(r) # Generate the values we want to plot plot_values = function1(r1) # Plot with correct extent matching our data range plt.imshow(plot_values, origin='lower', extent=[0, D, 0, D]) plt.colorbar(label='sin(r) Value') plt.xlabel('X') plt.ylabel('Y') plt.title('2D Density Plot of sin(√(X²+Y²))') plt.show()
This code will:
- Generate a valid 2D dataset for
imshow - Actually use your
function1()to calculate the sine values - Show the correct axis ranges (0 to 50) and a populated color plot instead of a blank one
内容的提问来源于stack exchange,提问作者Brandon SeedlessBananas Mc-Wil

