使用matplotlib.imshow绘制2D直方图遇TypeError错误的解决方法
解决2D直方图插值的问题
我来帮你搞定这个2D直方图的插值问题~首先得先搞清楚你报错的原因:ax.hist2d()返回的是一个元组(counts, xedges, yedges, image),里面包含了直方图的计数数组、x/y轴的bin边缘,还有默认绘制的图像对象。你直接把这个元组传给imshow(),它自然没法识别成可转换为float的图像数据,所以才会抛出TypeError。
下面给你几种可行的解决方案:
方案1:修正imshow()的使用方式
先从hist2d的返回值里提取出纯计数数组,再用imshow绘制并添加插值,还要注意坐标对齐的细节:
import matplotlib.pyplot as plt import numpy as np # 假设T和D是你的地震数据 # T = ... 你的数据 # D = ... 你的数据 fig, ax = plt.subplots(figsize=(8,6)) ax.set_title('Joint Distribution of NND for San Ramon Earthquakes') # 运行hist2d但保留返回值 counts, xedges, yedges, im = ax.hist2d(T, D, 30, density=True) # 先删掉hist2d默认画出来的原始图像 im.remove() # 用imshow绘制带插值的直方图,注意这几个关键参数: # - counts.T:转置数组,因为hist2d的counts是(xbins, ybins),imshow默认是(行,列)对应(y,x) # - origin='lower':让坐标原点和直方图的左下角对齐 # - extent:设置x和y轴的范围,和原始直方图一致 ax.imshow(counts.T, interpolation='bilinear', origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) # 添加颜色条,这里取ax上当前的图像对象 plt.colorbar(ax.images[0], ax=ax) plt.show()
你可以把interpolation改成'nearest'、'bicubic'等其他matplotlib支持的插值方式,调整平滑程度。
方案2:直接用numpy计算直方图数据,再可视化
跳过ax.hist2d(),先用numpy.histogram2d单独计算直方图的数值,再用imshow或pcolormesh绘制:
import numpy as np import matplotlib.pyplot as plt counts, xedges, yedges = np.histogram2d(T, D, bins=30, density=True) fig, ax = plt.subplots(figsize=(8,6)) ax.set_title('Joint Distribution of NND for San Ramon Earthquakes') # 用imshow绘制插值后的图 im = ax.imshow(counts.T, interpolation='bilinear', origin='lower', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) # 或者用pcolormesh加插值(设置shading='gouraud'实现平滑) # ax.pcolormesh(xedges, yedges, counts.T, shading='gouraud', cmap='viridis') plt.colorbar(im, ax=ax) plt.show()
替代方案:不用imshow也能实现平滑的2D分布
如果不想折腾直方图的插值,还有更简便的方法直接生成平滑的2D分布可视化:
方法A:核密度估计(KDE)
用seaborn的kdeplot直接生成平滑的密度热力图,非常适合展示数据的分布趋势:
import seaborn as sns import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8,6)) ax.set_title('Joint Distribution of NND for San Ramon Earthquakes') # fill=True 填充颜色,levels控制等高线数量,cmap选颜色映射 sns.kdeplot(x=T, y=D, fill=True, ax=ax, cmap='viridis', levels=20) plt.show()
方法B:六边形直方图(hexbin)
plt.hexbin绘制的六边形直方图自带一定的平滑感,比矩形直方图更柔和,也支持密度归一化:
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8,6)) ax.set_title('Joint Distribution of NND for San Ramon Earthquakes') # gridsize控制六边形的数量,数值越大越精细 hb = ax.hexbin(T, D, gridsize=30, density=True, cmap='viridis') plt.colorbar(hb, ax=ax) plt.show()
内容的提问来源于stack exchange,提问作者Senna
相关产品推荐
相关产品推荐

