You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绘制函数密度图时遭遇TypeError: Invalid dimensions for image data错误

解决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:

  • x and y are both 1D arrays created with linspace (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:09:58