带不规则分箱的极坐标等高线图绘制技术问询
解决方案
核心问题是你的数据采用了不规则方位角分箱(高仰角时分箱更粗),而默认的meshgrid生成的是规则网格,导致零值被错误绘制。以下是两种可行的解决方式:
方式1:填充规则网格(简单快速)
将高仰角行的零值分箱填充为对应合并分箱的数值,让网格变为规则,再用contourf或pcolormesh绘制:
import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mpl_colors # 加载数据 epfd = np.loadtxt("data.txt") # 处理最后一行(仰角87-90°):将三个120°分箱的数值填充到对应40个3°分箱中 epfd[29, 0:40] = epfd[29, 0] epfd[29, 40:80] = epfd[29, 40] epfd[29, 80:120] = epfd[29, 80] # 生成规则极坐标网格 azimuths = np.radians(np.arange(0, 360, 3)) els = np.arange(0, 90, 3) r, theta = np.meshgrid(els, azimuths) # 绘制极坐标图 fig, ax = plt.subplots(subplot_kw=dict(projection='polar')) im = ax.contourf(theta, r, epfd.T, norm=mpl_colors.LogNorm()) # 调整极坐标显示 ax.set_theta_direction(-1) ax.set_theta_offset(np.pi / 2.0) ax.invert_yaxis() # 天顶位于中心 # 添加颜色条 fig.colorbar(im, ax=ax, label='EPFD') plt.show()
方式2:绘制不规则分箱(精准匹配实际数据)
如果不想修改原始数据,可直接基于实际分箱边界创建多边形,用PolyCollection绘制,完全匹配你的分箱规则:
import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mpl_colors from matplotlib.collections import PolyCollection # 加载数据 epfd = np.loadtxt("data.txt") # 定义仰角(天顶距)分箱边界 zenith_distance_bins = 90 - np.arange(0, 91, 3) # 天顶距=90-仰角,中心为天顶 zd_rad = np.radians(zenith_distance_bins) # 定义每行的方位角分箱边界 theta_bins_list = [] for i in range(30): if i == 29: # 最后一行:3个120°分箱 theta_bins_list.append(np.arange(0, 361, 120)) else: # 其他行:120个3°分箱 theta_bins_list.append(np.arange(0, 361, 3)) # 构建多边形和对应颜色 polygons = [] colors = [] for row_idx in range(30): # 当前行的天顶距边界 zd_start, zd_end = zd_rad[row_idx], zd_rad[row_idx+1] # 当前行的方位角分箱(弧度) theta_bins = np.radians(theta_bins_list[row_idx]) # 当前行的数值 row_vals = epfd[row_idx] # 处理最后一行的数值映射 if row_idx == 29: row_vals = [row_vals[0], row_vals[40], row_vals[80]] # 生成每个分箱的四边形顶点 for bin_idx in range(len(theta_bins)-1): theta_start, theta_end = theta_bins[bin_idx], theta_bins[bin_idx+1] verts = [ (theta_start, zd_start), (theta_end, zd_start), (theta_end, zd_end), (theta_start, zd_end), ] polygons.append(verts) colors.append(row_vals[bin_idx]) # 绘制极坐标图 fig, ax = plt.subplots(subplot_kw=dict(projection='polar')) ax.set_theta_direction(-1) ax.set_theta_offset(np.pi / 2.0) ax.set_ylim(0, zd_rad[0]) # 天顶距最大为90°(仰角0°) # 添加多边形集合 pc = PolyCollection(polygons, edgecolors='none') pc.set_array(np.array(colors)) pc.set_norm(mpl_colors.LogNorm()) ax.add_collection(pc) # 添加颜色条 fig.colorbar(pc, ax=ax, label='EPFD') plt.show()
关键说明
- 极坐标映射:将天顶距(90°-仰角)作为极径
r,更符合天文图的习惯(中心为天顶)。 - 规则网格方式:通过填充零值分箱,快速适配
contourf的规则网格要求,适合快速可视化。 - 不规则分箱方式:精准匹配数据的实际分箱规则,无数据修改,适合专业天文可视化需求。
内容的提问来源于stack exchange,提问作者earnric
相关产品推荐
相关产品推荐

