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

Python使用matplotlib绘图脚本运行正常但图像不显示问题求助

问题描述

我是Python初学者,正在尝试进行绘图实操,编写的脚本可正常运行无报错,但最终没有显示图像,matplotlib和numpy库均已正确安装,运行环境为Ubuntu系统下的Python3。

问题代码
import numpy as np
f= h5py.File('3DIMG_05JUN2021_0000_L3B_HEM_DLY.h5','r')


                                           #通过打印HDF5包含的组来研究文件结构
for key in f.keys():
    print(key)                             #HDF5文件中的组名称
# 将会打印文件中的所有变量
                                           #获取HDF5组
ls=list(f.keys())
print("ls")
print(ls)
tsurf = f['HEM_DLY'][:]
print("tsurf")
print(tsurf)
tsurf1=np.squeeze(tsurf)
print(tsurf1.shape)

import matplotlib.pyplot as plt
im= plt.plot(tsurf1)
#plt.colorbar()
plt.imshow(im)
修复方案
  • 缺少h5py库导入:代码开头补import h5py,如果是临时运行没报错说明你之前在环境里手动导入过,正式脚本必须加上导入语句
  • 绘图逻辑错误:plt.plot()是用来画折线图的,返回值是Line2D对象列表,不是可可视化的数组,不能直接传给plt.imshow()。如果要可视化二维栅格数据,直接删掉im= plt.plot(tsurf1)这行,把tsurf1数组直接传给plt.imshow()即可
  • 缺少图像显示触发语句:matplotlib在Linux非交互式环境下默认不会主动弹出渲染窗口,所有绘图代码末尾必须加plt.show()才能弹出图像
  • 后端依赖缺失:如果加了plt.show()后报错,运行sudo apt install python3-tk安装matplotlib依赖的GUI渲染后端即可
修复后完整可运行代码
import numpy as np
import h5py
import matplotlib.pyplot as plt

# 读取HDF5文件
f = h5py.File('3DIMG_05JUN2021_0000_L3B_HEM_DLY.h5','r')

# 打印HDF5包含的组来研究文件结构
for key in f.keys():
    print(key) # HDF5文件中的组名称

# 获取HDF5组
ls = list(f.keys())
print("ls")
print(ls)
tsurf = f['HEM_DLY'][:]
print("tsurf")
print(tsurf)
tsurf1 = np.squeeze(tsurf)
print(tsurf1.shape)

# 绘图
plt.imshow(tsurf1)
plt.colorbar()
plt.show()

内容的提问来源于stack exchange,提问作者geet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:00:04