import os import re from pathlib import Path import numpy… · The Chat Archive
Explore import os import re from pathlib import Path import numpy as np import matplotlib.pyplot… Save Share Download ▾ Reportimport os
import re
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.font_manager import FontProperties, findfont
import geopandas as gpd
from shapely.prepared import prep
from shapely.geometry import Point
import cartopy.crs as ccrs
import pandas as pd
import mplcursors # 需安装:pip install mplcursors
===================== 字体配置(确保文字正常显示) =====================
def configure_font():
"""自动查找系统中的可用字体,确保中文正常显示"""
font_candidates = [
"SimHei", # 黑体
"Microsoft YaHei", # 微软雅黑
"SimSun", # 宋体
"WenQuanYi Micro Hei", # 文泉驿微米黑
"Heiti TC", # 繁体黑体
"DejaVu Sans", # fallback字体
"Arial" # 最终fallback
]
for font_name in font_candidates:
try:
# 尝试查找字体
font_path = findfont(FontProperties(family=font_name))
if os.path.exists(font_path):
print(f"使用字体: {font_name} ({font_path})")
return font_name
except:
continue
# 如果所有字体都找不到,使用默认设置
print("警告: 未找到合适的字体,可能导致文字显示异常")
return "DejaVu Sans"
配置全局字体
FONT_FAMILY = configure_font()
plt.rcParams["font.family"] = FONT_FAMILY
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
===================== 配置参数(修复顶部灰色) =====================
TXT_FILE = r"C:\Users\k\Desktop\08\fig_Z_OTHE_RADAMCR_RFST_20240820081800.066.bin.txt"
SHP_FILE = r"E:\shanxidixing\shanxi.shp"
EXCEL_FILE = r"C:\Users\k\Desktop\08\addation.xlsx" # 风电和光伏电站位置
强制限定经纬度范围(避免超出数据范围导致灰色)
FORCE_EXTENT = (105.0, 111.8, 31.2, 39.7) # (lon_min, lon_max, lat_min, lat_max)
核心显示配置
CLIP_TO_SHAPE = True # 只显示陕西范围
高对比度色带
cmap_list = [
(0.0, '#ffffff'), # 0.0 - 白色(极低概率)
(0.2, '#8ecae6'), # 0.2 - 亮蓝
(0.4, '#219ebc'), # 0.4 - 纯蓝
(0.6, '#ffb703'), # 0.6 - 亮黄
(0.8, '#fb8500'), # 0.8 - 橙色
(1.0, '#e63946') # 1.0 - 红色(高概率)
]
CMAP = LinearSegmentedColormap.from_list('HighContrastLightning', cmap_list)
VMIN, VMAX = 0.0, 1.0 # 概率范围
ALPHA = 1.0 # 不透明,颜色更浓郁
PAD_DEG = 0.3 # 适当留白,不超过数据范围
THRESHOLD = 0.05 # 过滤极低概率值
ZERO_ATOL = 1e-12 # 判断“等于0”的容差
WHITE_PROB_THRESHOLD = 0.1 # 低于此概率的区域显示为白色
FIG_DPI = 300 # 高分辨率
--- 电站标记样式 ---
风电站:菱形 + 深色描边
WIND_PLANT_MARKER = 'D'
WIND_PLANT_MARKERSIZE = 8
WIND_PLANT_EDGE = 'darkslategray'
WIND_PLANT_EDGE_WIDTH = 1.2
光伏电站:圆形 + 深色描边
PV_PLANT_MARKER = 'o'
PV_PLANT_MARKERSIZE = 8
PV_PLANT_EDGE = 'darkslategray'
PV_PLANT_EDGE_WIDTH = 1.2
PLANT_ZORDER = 6 # 确保在概率层上方
===================== 读取概率txt =====================
def read_prob_txt(txt_path, fallback_extent=FORCE_EXTENT):
"""返回 lon(1D), lat(1D), data(2D),支持多种格式解析"""
txt_path = str(txt_path)
# A) ESRI ASCII Grid 格式解析
try:
with open(txt_path, 'r', encoding='utf-8', errors='ignore') as f:
first6 = [f.readline() for _ in range(6)]
head = ''.join(first6).lower()
if all(k in head for k in ['ncols', 'nrows']) and
('xllcorner' in head or 'xllcenter' in head) and
('yllcorner' in head or 'yllcenter' in head) and
('cellsize' in head):
hdr = {}
for line in first6:
parts = line.split()
if len(parts) >= 2:
k = parts[0].lower()
try: v = float(parts[1])
except Exception:
try: v = int(parts[1])
except Exception: continue
hdr[k] = v
ncols, nrows, cell = int(hdr['ncols']), int(hdr['nrows']), float(hdr['cellsize'])
xll = float(hdr.get('xllcorner', hdr.get('xllcenter', 0.0)))
yll = float(hdr.get('yllcorner', hdr.get('yllcenter', 0.0)))
data = np.loadtxt(txt_path, skiprows=6).reshape(nrows, ncols)
# 计算中心点偏移
offset = 0.5 * cell if ('xllcorner' in hdr) or ('yllcorner' in hdr) else 0.0
lon = xll + offset + np.arange(ncols) * cell
lat = yll + offset + np.arange(nrows) * cell
# 确保纬度递增
if lat[0] > lat[-1]:
lat, data = lat[::-1], data[::-1, :]
# 处理无效值
nodata = hdr.get('nodata_value', None)
if nodata is not None:
data = np.where(np.isclose(data, nodata), np.nan, data)
return lon, lat, data
except Exception as e:
print(f"尝试解析ESRI ASCII Grid失败: {e}")
pass
AssistantCopy response Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider Unknown
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Added to archive Nov 19, 2026
ID 01m7tp99965nsb07cz3pwrt9tmSource & license Imported from Arena Expert 5K (source ). Imported records earn no Research Points.
Upstream record: 5157df77-ae38-4f68-8e6b-ef7f9df96443:b
LMArena, Arena Expert (2025). https://news.lmarena.ai/arena-expert/
License: Prompts CC-BY-4.0; outputs governed by provider terms
Dataset releases Not yet included in a published release.
# B) 三列 (lon, lat, val) 格式解析
try:
arr = np.loadtxt(txt_path)
if arr.ndim == 1:
arr = arr.reshape(1, -1)
if arr.ndim == 2 and arr.shape[1] == 3:
lon_r, lat_r, vals = np.round(arr[:, 0], 6), np.round(arr[:, 1], 6), arr[:, 2]
lon_u, lat_u = np.unique(lon_r), np.unique(lat_r)
grid = np.full((lat_u.size, lon_u.size), np.nan, dtype=float)
lon_ix, lat_ix = {v: i for i, v in enumerate(lon_u)}, {v: i for i, v in enumerate(lat_u)}
for x, y, v in zip(lon_r, lat_r, vals):
grid[lat_ix[y], lon_ix[x]] = v
if lat_u[0] > lat_u[-1]:
lat_u, grid = lat_u[::-1], grid[::-1, :]
return lon_u, lat_u, grid
except Exception as e:
print(f"尝试解析三列数据失败: {e}")
pass
# C) 纯二维矩阵格式解析
try:
data = np.loadtxt(txt_path)
ny, nx = data.shape
lon_min, lon_max, lat_min, lat_max = fallback_extent
lon = np.linspace(lon_min, lon_max, nx)
lat = np.linspace(lat_min, lat_max, ny)
if lat[0] > lat[-1]:
lat, data = lat[::-1], data[::-1, :]
return lon, lat, data
except Exception as e:
raise IOError(f"无法解析文件 '{txt_path}' 为任何已知格式: {e}")
===================== 读取Shapefile ===================== def load_sx_shapefile(shp_path):
"""加载并预处理陕西省Shapefile,返回GeoDataFrame和合并的几何对象"""
try:
gdf = gpd.read_file(shp_path)
except Exception as e:
print(f"错误:无法读取 Shapefile '{shp_path}': {e}")
return gpd.GeoDataFrame(), None
# 统一坐标系为WGS84 (EPSG:4326)
if gdf.crs is None:
print("提示:未检测到CRS,按WGS84经纬度处理。")
gdf.crs = "EPSG:4326"
elif gdf.crs.to_string().upper() not in ("EPSG:4326", "EPSG:4490"):
gdf = gdf.to_crs(epsg=4326)
else:
gdf = gdf.to_crs(epsg=4326)
if gdf.empty:
print(f"警告:Shapefile '{shp_path}' 读取为空。")
return gdf, None
# 合并几何对象(用于裁剪)
union_geom = None
try:
if hasattr(gdf.geometry, 'union_all'):
union_geom = gdf.geometry.union_all()
else:
union_geom = gdf.geometry.unary_union
# 修复无效几何
if not union_geom.is_valid:
print("警告:合并的几何体无效,尝试修复...")
union_geom = union_geom.buffer(0)
if not union_geom.is_valid:
print("警告:几何体修复失败。")
union_geom = None
except Exception as e:
print(f"警告:无法创建几何体合并:{e}。")
union_geom = None
return gdf, union_geom
===================== 栅格裁剪 ===================== def clip_grid_by_polygon(lon, lat, data, polygon):
"""根据多边形裁剪栅格数据,多边形外的区域设为NaN"""
xx, yy = np.meshgrid(lon, lat)
P = prep(polygon)
# 逐点判断是否在多边形内
flat_mask = np.array([P.covers(Point(x, y)) for x, y in zip(xx.ravel(), yy.ravel())])
mask = flat_mask.reshape(data.shape)
return np.where(mask, data, np.nan)
===================== 读取风电与光伏电站位置 ===================== def read_all_plant_locations(excel_path):
"""从Excel读取风电站(2-189行)和光伏电站(191-416行)的经纬度"""
def _read_and_process(skip, num_rows, plant_type):
"""内部函数:读取指定范围的电站数据并清洗"""
try:
df = pd.read_excel(excel_path, skiprows=skip, nrows=num_rows, header=None)
if df.empty:
print(f"信息: 未在指定行范围读取到{plant_type}数据。")
return np.array([]), np.array([])
# 假设第三列(索引2)是经度,第四列(索引3)是纬度
lon = pd.to_numeric(df.iloc[:, 2], errors='coerce').values
lat = pd.to_numeric(df.iloc[:, 3], errors='coerce').values
# 过滤无效值
valid_mask = ~np.isnan(lon) & ~np.isnan(lat)
lon, lat = lon[valid_mask], lat[valid_mask]
print(f"已从 '{excel_path}' 读取 {len(lon)} 个有效的{plant_type}位置。")
return lon, lat
except Exception as e:
print(f"读取{plant_type}数据时发生错误: {e}")
return np.array([]), np.array([])
try:
# 风电站: 从第2行开始(skip=1),共188行(189-2+1)
wind_lon, wind_lat = _read_and_process(skip=1, num_rows=188, plant_type="风电站")
# 光伏电站: 从第191行开始(skip=190),共226行(416-191+1)
pv_lon, pv_lat = _read_and_process(skip=190, num_rows=226, plant_type="光伏电站")
return (wind_lon, wind_lat), (pv_lon, pv_lat)
except FileNotFoundError:
print(f"错误: Excel文件 '{excel_path}' 未找到。")
return (np.array([]), np.array([])), (np.array([]), np.array([]))
===================== 绘图函数(修复顶部灰色) ===================== def plot_prob_with_shp(lon, lat, data, shp_gdf, shp_union, out_png,
title='陕西省雷电落区概率', clip_to_shape=True,
cmap=CMAP, vmin=VMIN, vmax=VMAX, alpha=ALPHA,
pad_deg=PAD_DEG, threshold=THRESHOLD, zero_atol=ZERO_ATOL,
white_prob_threshold=WHITE_PROB_THRESHOLD,
wind_locations=None, pv_locations=None,
dpi=FIG_DPI, show=False):
proj = ccrs.PlateCarree() # 地理投影
# 数据预处理
data = np.array(data, dtype=float)
# 应用概率阈值过滤
if threshold is not None:
data = np.where(data >= float(threshold), data, np.nan)
# 按省份边界裁剪
if clip_to_shape and shp_union is not None:
data = clip_grid_by_polygon(lon, lat, data, shp_union)
# 复制数据用于绘图
data_plot = np.array(data, dtype=float, copy=True)
# 低概率区域设为白色
if white_prob_threshold is not None:
mask_low_prob = np.isfinite(data_plot) & (data_plot <= max(vmin, min(vmax, white_prob_threshold)))
data_plot[mask_low_prob] = np.nan
# 零值区域设为透明
mask_zero = np.isfinite(data_plot) & (np.abs(data_plot) <= zero_atol)
data_plot[mask_zero] = np.nan
# 处理无效值为掩码
data_plot = np.ma.masked_invalid(data_plot)
# 配置色带
cmap_obj = cmap.copy()
cmap_obj.set_bad((1, 1, 1, 1)) # 无效值区域为白色
# 强制使用预设的经纬度范围,避免超出数据导致灰色
lon_min, lon_max, lat_min, lat_max = FORCE_EXTENT
extent = [
lon_min - pad_deg,
lon_max + pad_deg,
lat_min - pad_deg,
lat_max + pad_deg
]
# 创建图形,强制背景为白色
fig = plt.figure(figsize=(10, 12), dpi=dpi, facecolor='white')
ax = plt.axes(projection=proj)
ax.set_extent(extent, crs=proj)
ax.set_facecolor('white') # 关键修复:将背景色强制设为白色
# 绘制省份底图
if not shp_gdf.empty:
# 省份内部填充浅灰色,不覆盖边缘
ax.add_geometries(shp_gdf.geometry, crs=proj,
facecolor='#f8f8f8', edgecolor='none', zorder=1)
# 省份边界加粗
ax.add_geometries(shp_gdf.geometry, crs=proj,
facecolor='none', edgecolor='#222222',
linewidth=2.0, zorder=5)
# 计算栅格边缘,确保与数据范围精确匹配
if len(lon) > 1:
lon_step = (lon[-1] - lon[0]) / (len(lon) - 1) if len(lon) > 1 else 0.01
lon_edges = np.concatenate((
[lon[0] - lon_step / 2],
(lon[:-1] + lon[1:]) / 2,
[lon[-1] + lon_step / 2]
))
else:
lon_edges = np.array([lon[0] - 0.005, lon[0] + 0.005])
if len(lat) > 1:
lat_step = (lat[-1] - lat[0]) / (len(lat) - 1) if len(lat) > 1 else 0.01
lat_edges = np.concatenate((
[lat[0] - lat_step / 2],
(lat[:-1] + lat[1:]) / 2,
[lat[-1] + lat_step / 2]
))
else:
lat_edges = np.array([lat[0] - 0.005, lat[0] + 0.005])
X, Y = np.meshgrid(lon_edges, lat_edges)
# 绘制概率色斑图,确保覆盖整个有效范围
im = ax.pcolormesh(
X, Y, data_plot,
cmap=cmap_obj,
vmin=vmin,
vmax=vmax,
shading='flat',
transform=proj,
alpha=alpha,
zorder=2
)
# 添加经纬度标签(不显示网格线)
gl = ax.gridlines(
crs=proj,
draw_labels=True,
linewidth=0, # 网格线宽度设为0,不显示虚线
color='#bbbbbb',
alpha=0, # 网格线透明度设为0,完全隐藏
linestyle='--'
)
gl.top_labels, gl.right_labels = False, False
gl.xlocator = mticker.FixedLocator(np.arange(lon_min, lon_max + 1, 1))
gl.ylocator = mticker.FixedLocator(np.arange(lat_min, lat_max + 1, 1))
# 调整经纬度标签字体大小为14
gl.xlabel_style = {'size': 14, 'color': '#333333', 'weight': 'bold'}
gl.ylabel_style = {'size': 14, 'color': '#333333', 'weight': 'bold'}
# 调整色标位置,避免溢出
cbar = plt.colorbar(
im,
ax=ax,
shrink=0.82, # 缩小色标,避免超出图形范围
pad=0.03, # 调整与图形的间距
ticks=np.arange(0, 1.1, 0.2)
)
cbar.set_label('雷电风险发生概率', fontsize=16, color='#333333', weight='bold')
cbar.ax.tick_params(labelsize=14, colors='#333333')
cbar.outline.set_linewidth(1.5)
# 计算电站位置对应的概率值
wind_probs = None
pv_probs = None
# 绘制风电站标记
has_legend = False
if wind_locations and len(wind_locations[0]) > 0:
wind_lon, wind_lat = wind_locations
wind_probs = np.array([
data[np.argmin(np.abs(lat - plat)), np.argmin(np.abs(lon - plon))]
for plon, plat in zip(wind_lon, wind_lat)
])
valid_mask = np.isfinite(wind_probs)
wind_lon, wind_lat, wind_probs = wind_lon[valid_mask], wind_lat[valid_mask], wind_probs[valid_mask]
ax.scatter(
wind_lon, wind_lat,
c=wind_probs,
cmap=cmap_obj,
vmin=vmin,
vmax=vmax,
marker=WIND_PLANT_MARKER,
s=WIND_PLANT_MARKERSIZE**2,
edgecolor=WIND_PLANT_EDGE,
linewidth=WIND_PLANT_EDGE_WIDTH,
transform=proj,
zorder=PLANT_ZORDER,
label='风电站'
)
has_legend = True
# 绘制光伏电站标记
if pv_locations and len(pv_locations[0]) > 0:
pv_lon, pv_lat = pv_locations
pv_probs = np.array([
data[np.argmin(np.abs(lat - plat)), np.argmin(np.abs(lon - plon))]
for plon, plat in zip(pv_lon, pv_lat)
])
valid_mask = np.isfinite(pv_probs)
pv_lon, pv_lat, pv_probs = pv_lon[valid_mask], pv_lat[valid_mask], pv_probs[valid_mask]
ax.scatter(
pv_lon, pv_lat,
c=pv_probs,
cmap=cmap_obj,
vmin=vmin,
vmax=vmax,
marker=PV_PLANT_MARKER,
s=PV_PLANT_MARKERSIZE**2,
edgecolor=PV_PLANT_EDGE,
linewidth=PV_PLANT_EDGE_WIDTH,
transform=proj,
zorder=PLANT_ZORDER,
label='光伏电站'
)
has_legend = True
# 添加图例(调整到左上角)
if has_legend:
legend = ax.legend(
loc='upper left', # 图例位置改为左上角
frameon=True,
fontsize=16,
facecolor='white',
edgecolor='#aaaaaa',
framealpha=1.0,
labelspacing=0.8,
borderpad=0.8
)
legend.get_texts()[0].set_color('#333333')
legend.get_texts()[0].set_weight('bold')
legend.get_frame().set_linewidth(1.5)
# 添加标题
#ax.set_title('20240820161800', fontsize=18, pad=20, fontweight='bold', color='#222222')
# 添加交互功能
cursor = mplcursors.cursor(hover=True)
@cursor.connect("add")
def on_hover(sel):
"""鼠标悬停时显示详细信息"""
if hasattr(sel.artist, 'get_label'):
label = sel.artist.get_label()
if label == '风电站' and wind_probs is not None:
point_idx = np.argmin(np.hypot(wind_lon - sel.target[0], wind_lat - sel.target[1]))
lon_val = round(wind_lon[point_idx], 2)
lat_val = round(wind_lat[point_idx], 2)
prob_val = round(wind_probs[point_idx], 2)
sel.annotation.set_text(f"{label}\n经度: {lon_val}\n纬度: {lat_val}\n雷电概率: {prob_val}")
return
elif label == '光伏电站' and pv_probs is not None:
point_idx = np.argmin(np.hypot(pv_lon - sel.target[0], pv_lat - sel.target[1]))
lon_val = round(pv_lon[point_idx], 2)
lat_val = round(pv_lat[point_idx], 2)
prob_val = round(pv_probs[point_idx], 2)
sel.annotation.set_text(f"{label}\n经度: {lon_val}\n纬度: {lat_val}\n雷电概率: {prob_val}")
return
# 概率区域信息
lon_idx = np.argmin(np.abs(lon - sel.target[0]))
lat_idx = np.argmin(np.abs(lat - sel.target[1]))
if 0 <= lon_idx < len(lon) and 0 <= lat_idx < len(lat):
prob_val = data_plot[lat_idx, lon_idx]
if not np.ma.is_masked(prob_val):
lon_val = round(sel.target[0], 2)
lat_val = round(sel.target[1], 2)
sel.annotation.set_text(f"经度: {lon_val}\n纬度: {lat_val}\n概率: {prob_val:.2f}")
else:
sel.annotation.set_text(f"经度: {round(sel.target[0], 2)}\n纬度: {round(sel.target[1], 2)}\n无数据")
# 保存与显示,确保不裁剪内容
plt.tight_layout()
plt.savefig(
out_png,
dpi=dpi,
bbox_inches='tight', # 精确裁剪边界
facecolor='white', # 确保保存时背景为白色
pad_inches=0.1 # 最小化额外边距
)
print('已保存图像:', out_png)
if show:
plt.show()
plt.close(fig)
===================== 主流程 ===================== def main():
# 读取雷电概率数据
lon, lat, grid = read_prob_txt(TXT_FILE, fallback_extent=FORCE_EXTENT)
# 过滤异常值
grid = np.where((grid <= -1e20) | (grid < -9990), np.nan, grid)
# 读取陕西省Shapefile
sx_gdf, sx_union = load_sx_shapefile(SHP_FILE)
# 读取电站位置
wind_locs, pv_locs = read_all_plant_locations(EXCEL_FILE)
# 生成输出文件名
stem = Path(TXT_FILE).stem
title = re.sub(r'^fig_', '', stem).replace('.bin', '')
out_png = os.path.join(Path(TXT_FILE).parent, f"{stem}_雷电概率与电站分布.png")
# 绘图
plot_prob_with_shp(
lon, lat, grid, sx_gdf, sx_union, out_png,
title=title,
clip_to_shape=CLIP_TO_SHAPE,
cmap=CMAP, vmin=VMIN, vmax=VMAX,
alpha=ALPHA, pad_deg=PAD_DEG,
threshold=THRESHOLD, zero_atol=ZERO_ATOL,
white_prob_threshold=WHITE_PROB_THRESHOLD,
wind_locations=wind_locs,
pv_locations=pv_locs,
dpi=FIG_DPI,
show=True
)
if name == 'main ':
main()
我想将上面这个程序的字体配置逻辑,横纵坐标的配置逻辑,地图显示的配置逻辑修改到我下面的这个我自己的程序里:
import os
import re
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.colors as mcolors
import geopandas as gpd
from shapely.prepared import prep
from shapely.geometry import Point
import cartopy.crs as ccrs
import pandas as pd
from matplotlib.lines import Line2D # 新增用于自定义图例
===================== 配置 ===================== TXT_FILE = r"C:\Users\k\Desktop\08\fig_Z_OTHE_RADAMCR_RFST_20240820081800.066.bin.txt"
SHP_FILE = r"E:\shanxidixing\shanxi.shp"
EXCEL_FILE = r"C:\Users\k\Desktop\08\addation.xlsx" # 新能源电站位置信息Excel文件
若txt为纯矩阵时使用的经纬度范围 FALLBACK_EXTENT = (105.0, 111.8, 31.2, 39.7) # (lon_min, lon_max, lat_min, lat_max)
CLIP_TO_SHAPE = True # 是否只显示陕西范围
CMAP = "turbo" # 颜色表
VMIN, VMAX = 0.0, 1.0 # 概率范围(保持0~1即可,0会被透明处理)
ALPHA = 0.95 # 色斑透明度
PAD_DEG = 0.5 # 视域留白(度)
THRESHOLD = None # 可选阈值,例如 0.05 (低于此值的数据将被视为NaN)
ZERO_ATOL = 1e-12 # 判断“等于0”的容差(防止浮点误差)
WHITE_PROB_THRESHOLD = 0.1 # 概率低于此值的区域显示为白色
FIG_DPI = 220
风电站标记样式 (第2-189行) WIND_MARKER = '^' # 三角形
WIND_MARKERSIZE = 8 # 标记大小
WIND_ZORDER = 4 # 绘图层级
光伏电站标记样式 (第191-416行) SOLAR_MARKER = 'o' # 圆形
SOLAR_MARKERSIZE = 8 # 标记大小
SOLAR_ZORDER = 4 # 绘图层级
===================== 读取概率txt ===================== def read_prob_txt(txt_path, fallback_extent=(105, 112, 31, 40)):
"""
返回 lon(1D), lat(1D), data(2D)
支持:A) ESRI ASCII Grid 头 B) 三列:lon lat val C) 仅二维矩阵
"""
txt_path = str(txt_path)
# A) ESRI ASCII Grid
try:
with open(txt_path, 'r', encoding='utf-8', errors='ignore') as f:
first6 = [f.readline() for _ in range(6)]
head = ''.join(first6).lower()
if all(k in head for k in ['ncols', 'nrows']) and \
('xllcorner' in head or 'xllcenter' in head) and \
('yllcorner' in head or 'yllcenter' in head) and \
('cellsize' in head):
hdr = {}
for line in first6:
parts = line.split()
if len(parts) >= 2:
k = parts[0].lower()
try:
v = float(parts[1])
except Exception:
try:
v = int(parts[1])
except Exception:
continue
hdr[k] = v
ncols = int(hdr['ncols'])
nrows = int(hdr['nrows'])
cell = float(hdr['cellsize'])
xll = float(hdr.get('xllcorner', hdr.get('xllcenter', 0.0)))
yll = float(hdr.get('yllcorner', hdr.get('yllcenter', 0.0)))
data = np.loadtxt(txt_path, skiprows=6).reshape(nrows, ncols)
# 网格中心坐标
use_corner = ('xllcorner' in hdr) or ('yllcorner' in hdr)
offset = 0.5 * cell if use_corner else 0.0
lon = xll + offset + np.arange(ncols) * cell
lat = yll + offset + np.arange(nrows) * cell
# 确保纬度是递增顺序
if lat[0] > lat[-1]:
lat = lat[::-1]; data = data[::-1, :]
nodata = hdr.get('nodata_value', None)
if nodata is not None:
data = np.where(np.isclose(data, nodata), np.nan, data)
return lon, lat, data
except Exception as e:
print(f"尝试解析ESRI ASCII Grid失败: {e}")
pass
# B) 三列 lon lat val
try:
arr = np.loadtxt(txt_path)
if arr.ndim == 1:
arr = arr.reshape(1, -1)
if arr.ndim == 2 and arr.shape[1] == 3:
lon_r = np.round(arr[:, 0], 6)
lat_r = np.round(arr[:, 1], 6)
vals = arr[:, 2]
lon_u = np.unique(lon_r)
lat_u = np.unique(lat_r)
nlon, nlat = lon_u.size, lat_u.size
grid = np.full((nlat, nlon), np.nan, dtype=float)
lon_ix = {v: i for i, v in enumerate(lon_u)}
lat_ix = {v: i for i, v in enumerate(lat_u)}
for x, y, v in zip(lon_r, lat_r, vals):
grid[lat_ix[y], lon_ix[x]] = v
if lat_u[0] > lat_u[-1]:
lat_u = lat_u[::-1]; grid = grid[::-1, :]
return lon_u, lat_u, grid
except Exception as e:
print(f"尝试解析三列数据失败: {e}")
pass
# C) 仅二维矩阵
try:
data = np.loadtxt(txt_path)
ny, nx = data.shape
lon_min, lon_max, lat_min, lat_max = fallback_extent
lon = np.linspace(lon_min, lon_max, nx)
lat = np.linspace(lat_min, lat_max, ny)
if lat[0] > lat[-1]:
lat = lat[::-1]; data = data[::-1, :]
return lon, lat, data
except Exception as e:
raise IOError(f"无法解析文件 '{txt_path}' 为任何已知格式: {e}")
===================== Shapefile ===================== def load_sx_shapefile(shp_path):
try:
gdf = gpd.read_file(shp_path)
except Exception as e:
print(f"错误:无法读取 Shapefile '{shp_path}': {e}")
return gpd.GeoDataFrame(), None
# 统一到WGS84经纬度
if gdf.crs is None:
print("提示:未检测到CRS,按WGS84经纬度处理。")
elif gdf.crs.to_string().upper() not in ("EPSG:4326", "EPSG:4490"):
gdf = gdf.to_crs(epsg=4326)
else:
gdf = gdf.to_crs(epsg=4326)
if gdf.empty:
print(f"警告:Shapefile '{shp_path}' 读取为空。")
return gdf, None
union_geom = None
try:
if hasattr(gdf.geometry, 'union_all'):
union_geom = gdf.geometry.union_all()
else:
union_geom = gdf.geometry.unary_union
if not union_geom.is_valid:
print("警告:合并的几何体无效,尝试修复...")
union_geom = union_geom.buffer(0)
if not union_geom.is_valid:
print("警告:几何体修复失败。裁剪可能不准确。")
union_geom = None
except Exception as e:
print(f"警告:无法创建几何体合并:{e}。形状裁剪将被跳过。")
union_geom = None
return gdf, union_geom
===================== 栅格裁剪 ===================== def clip_grid_by_polygon(lon, lat, data, polygon):
xx, yy = np.meshgrid(lon, lat)
P = prep(polygon)
flat_mask = np.array([P.covers(Point(x, y)) for x, y in zip(xx.ravel(), yy.ravel())])
mask = flat_mask.reshape(data.shape)
return np.where(mask, data, np.nan)
===================== 读取新能源电站位置(区分风电/光伏) ===================== def read_plant_locations(excel_path):
"""
从Excel文件中读取新能源电站的经纬度,区分风电站和光伏电站:
- 风电站:Excel第2行至189行(DataFrame索引0-187)
- 光伏电站:Excel第191行至416行(DataFrame索引189-414)
返回:(风电站经度, 风电站纬度, 光伏电站经度, 光伏电站纬度)
"""
try:
# 跳过第1行(表头),读取所有数据
df = pd.read_excel(excel_path, skiprows=1, header=None)
total_rows = len(df)
print(f"已读取Excel文件,共 {total_rows} 行数据")
# 定义行索引范围(注意:DataFrame索引从0开始,对应Excel第2行)
# 风电站:Excel第2行(索引0)到第189行(索引188-1=187)
wind_start_idx = 0
wind_end_idx = 187 # 189-2 = 187(因为索引0对应第2行)
# 光伏电站:Excel第191行(索引190)到第416行(索引415)
solar_start_idx = 189 # 191-2 = 189
solar_end_idx = 414 # 416-2 = 414
# 裁剪超出实际数据范围的索引
wind_end_idx = min(wind_end_idx, total_rows - 1)
solar_start_idx = max(solar_start_idx, 0)
solar_end_idx = min(solar_end_idx, total_rows - 1)
# 提取风电站数据(第三列经度-索引2,第四列纬度-索引3)
wind_lon = df.iloc[wind_start_idx:wind_end_idx+1, 2].values.astype(float)
wind_lat = df.iloc[wind_start_idx:wind_end_idx+1, 3].values.astype(float)
print(f"已提取风电站数据:{len(wind_lon)} 个站点(索引 {wind_start_idx}-{wind_end_idx})")
# 提取光伏电站数据
solar_lon = df.iloc[solar_start_idx:solar_end_idx+1, 2].values.astype(float)
solar_lat = df.iloc[solar_start_idx:solar_end_idx+1, 3].values.astype(float)
print(f"已提取光伏电站数据:{len(solar_lon)} 个站点(索引 {solar_start_idx}-{solar_end_idx})")
return wind_lon, wind_lat, solar_lon, solar_lat
except FileNotFoundError:
print(f"错误: Excel文件 '{excel_path}' 未找到。")
return np.array([]), np.array([]), np.array([]), np.array([])
except IndexError:
print("错误: Excel文件列数不足或经纬度列索引不正确。")
print("预期第三列(索引2)为经度,第四列(索引3)为纬度。")
return np.array([]), np.array([]), np.array([]), np.array([])
except Exception as e:
print(f"读取Excel文件时发生错误: {e}")
return np.array([]), np.array([]), np.array([]), np.array([])
===================== 绘图函数 ===================== def plot_prob_with_shp(lon, lat, data, shp_gdf, shp_union, out_png,
title='陕西省雷电落区概率', clip_to_shape=True,
cmap="turbo", vmin=0.0, vmax=1.0, alpha=0.95,
pad_deg=0.5, threshold=None, zero_atol=1e-12,
white_prob_threshold=None,
wind_lon=None, wind_lat=None, # 风电站位置
solar_lon=None, solar_lat=None, # 光伏电站位置
dpi=220, show=False):
proj = ccrs.PlateCarree()
# 可选阈值处理
if threshold is not None:
data = np.where(data >= float(threshold), data, np.nan)
# 裁剪处理
print(f"DEBUG: 裁剪前数据形状: {data.shape}, NaN数量: {np.sum(np.isnan(data))}")
if clip_to_shape and shp_union is not None:
initial_nan_count = np.sum(np.isnan(data))
data = clip_grid_by_polygon(lon, lat, data, shp_union)
clipped_nan_count = np.sum(np.isnan(data))
print(f"DEBUG: 裁剪后数据形状: {data.shape}, 裁剪前NaN: {initial_nan_count}, 裁剪后NaN: {clipped_nan_count}")
elif clip_to_shape and shp_union is None:
print("警告: 无法执行形状裁剪,shp_union为空或无效。")
# 准备绘图数据
data_plot = np.array(data, dtype=float, copy=True)
# 低概率区域设为白色
if white_prob_threshold is not None and vmin is not None and vmax is not None:
effective_white_threshold = max(vmin, min(vmax, white_prob_threshold))
mask_low_prob = np.isfinite(data_plot) & (data_plot <= effective_white_threshold)
data_plot[mask_low_prob] = np.nan
# 0值设为透明
mask_zero = np.isfinite(data_plot) & (np.abs(data_plot) <= zero_atol)
data_plot[mask_zero] = np.nan
data_plot = np.ma.masked_invalid(data_plot)
# 配置颜色表
cmap_obj = plt.get_cmap(cmap)
if hasattr(cmap_obj, "copy"):
cmap_obj = cmap_obj.copy()
cmap_obj.set_bad((1, 1, 1, 1)) # NaN值显示为白色
# 确定显示范围
extent = None
if not shp_gdf.empty and shp_gdf.total_bounds is not None:
bounds = shp_gdf.total_bounds
if np.all(np.isfinite(bounds)) and len(bounds) == 4:
minx, miny, maxx, maxy = bounds
extent = [minx - pad_deg, maxx + pad_deg, miny - pad_deg, maxy + pad_deg]
else:
print("警告: Shapefile边界无效,使用数据网格范围。")
if extent is None:
print("使用数据网格范围作为显示范围。")
min_lon, max_lon = np.min(lon), np.max(lon)
min_lat, max_lat = np.min(lat), np.max(lat)
extent = [min_lon - pad_deg, max_lon + pad_deg, min_lat - pad_deg, max_lat + pad_deg]
# 创建图形
fig = plt.figure(figsize=(10, 12), dpi=dpi, facecolor='white')
ax = plt.axes(projection=proj)
ax.set_extent(extent, crs=proj)
ax.set_facecolor('white')
# 绘制陕西区域
if not shp_gdf.empty:
ax.add_geometries(shp_gdf.geometry, crs=proj,
facecolor='white', edgecolor='none', zorder=1)
ax.add_geometries(shp_gdf.geometry, crs=proj,
facecolor='none', edgecolor='black', linewidth=0.9, zorder=3)
# 计算网格边缘坐标
if len(lon) > 1:
lon_diff = np.diff(lon)
lon_edges = np.concatenate(([lon[0] - lon_diff[0]/2], lon[:-1] + lon_diff/2, [lon[-1] + lon_diff[-1]/2]))
else:
lon_edges = np.array([lon[0] - 0.005, lon[0] + 0.005])
if len(lat) > 1:
lat_diff = np.diff(lat)
lat_edges = np.concatenate(([lat[0] - lat_diff[0]/2], lat[:-1] + lat_diff/2, [lat[-1] + lat_diff[-1]/2]))
else:
lat_edges = np.array([lat[0] - 0.005, lat[0] + 0.005])
X, Y = np.meshgrid(lon_edges, lat_edges)
# 绘制概率栅格
im = ax.pcolormesh(X, Y, data_plot, cmap=cmap_obj, vmin=vmin, vmax=vmax,
shading='flat', transform=proj, alpha=alpha, zorder=2)
# 只保留横纵坐标值,不保留刻度线
xticks = np.linspace(extent[0], extent[1], num=7)
yticks = np.linspace(extent[2], extent[3], num=7)
ax.set_xticks(xticks, crs=proj)
ax.set_yticks(yticks, crs=proj)
lon_formatter = mticker.FormatStrFormatter('%.1f°E')
lat_formatter = mticker.FormatStrFormatter('%.1f°N')
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
ax.tick_params(labelsize=10, length=0) # length=0去除刻度线
# 不添加ax.gridlines
# 添加颜色条
cbar = plt.colorbar(im, ax=ax, shrink=0.92, pad=0.03)
cbar.set_label('雷电风险落区概率')
# ============== 绘制风电站位置 ==============
wind_scatter = None
if wind_lon is not None and wind_lat is not None and len(wind_lon) > 0:
# 获取风电站概率值
wind_probabilities = []
for plon, plat in zip(wind_lon, wind_lat):
lon_idx = np.argmin(np.abs(lon - plon))
lat_idx = np.argmin(np.abs(lat - plat))
prob = data_plot[lat_idx, lon_idx] if (lat_idx < data_plot.shape[0] and lon_idx < data_plot.shape[1]) else np.nan
wind_probabilities.append(prob)
wind_probabilities = np.array(wind_probabilities)
# 绘制风电站(三角形)
wind_scatter = ax.scatter(wind_lon, wind_lat,
c=wind_probabilities,
cmap=cmap_obj,
vmin=vmin, vmax=vmax,
marker=WIND_MARKER,
s=WIND_MARKERSIZE**2,
edgecolor='black',
linewidth=0.5,
transform=proj,
zorder=WIND_ZORDER,
label='风电站')
# ============== 绘制光伏电站位置 ==============
solar_scatter = None
if solar_lon is not None and solar_lat is not None and len(solar_lon) > 0:
# 获取光伏电站概率值
solar_probabilities = []
for plon, plat in zip(solar_lon, solar_lat):
lon_idx = np.argmin(np.abs(lon - plon))
lat_idx = np.argmin(np.abs(lat - plat))
prob = data_plot[lat_idx, lon_idx] if (lat_idx < data_plot.shape[0] and lon_idx < data_plot.shape[1]) else np.nan
solar_probabilities.append(prob)
solar_probabilities = np.array(solar_probabilities)
# 绘制光伏电站(圆形)
solar_scatter = ax.scatter(solar_lon, solar_lat,
c=solar_probabilities,
cmap=cmap_obj,
vmin=vmin, vmax=vmax,
marker=SOLAR_MARKER,
s=SOLAR_MARKERSIZE**2,
edgecolor='black',
linewidth=0.5,
transform=proj,
zorder=SOLAR_ZORDER,
label='光伏电站')
# 添加图例(左上角,且三角形和圆形为纯白色)
if (wind_lon is not None and len(wind_lon) > 0) or (solar_lon is not None and len(solar_lon) > 0):
legend_elements = []
# 风电站(三角形,白色)
legend_elements.append(Line2D([0], [0], marker=WIND_MARKER, color='w', label='风电站',
markerfacecolor='white', markeredgecolor='black',
markersize=WIND_MARKERSIZE, linestyle='None', linewidth=0.5))
# 光伏电站(圆形,白色)
legend_elements.append(Line2D([0], [0], marker=SOLAR_MARKER, color='w', label='光伏电站',
markerfacecolor='white', markeredgecolor='black',
markersize=SOLAR_MARKERSIZE, linestyle='None', linewidth=0.5))
ax.legend(handles=legend_elements, loc='upper left', frameon=True, fontsize=10)
# 去除标题
# ax.set_title(title, fontsize=12, pad=12)
plt.tight_layout()
plt.savefig(out_png, dpi=dpi, bbox_inches='tight', facecolor='white')
if show:
plt.show()
plt.close(fig)
print('已保存:', out_png)
===================== 主流程 ===================== def main():
# 读取概率数据
lon, lat, grid = read_prob_txt(TXT_FILE, fallback_extent=FALLBACK_EXTENT)
# 清理无效值
grid = np.where((grid <= -1e20) | (grid < -9990), np.nan, grid)
# 读取陕西边界
sx_gdf, sx_union = load_sx_shapefile(SHP_FILE)
# 读取电站位置(区分风电/光伏)
wind_lon, wind_lat, solar_lon, solar_lat = read_plant_locations(EXCEL_FILE)
# 生成输出文件名
stem = Path(TXT_FILE).stem
title = re.sub(r'^fig_', '', stem).replace('.bin', '')
out_png = os.path.join(Path(TXT_FILE).parent, f"{stem}_SX_probability_plants_separated.png")
# 绘图
plot_prob_with_shp(
lon, lat, grid, sx_gdf, sx_union, out_png,
title=title,
clip_to_shape=CLIP_TO_SHAPE,
cmap=CMAP, vmin=VMIN, vmax=VMAX,
alpha=ALPHA, pad_deg=PAD_DEG,
threshold=THRESHOLD, zero_atol=ZERO_ATOL,
white_prob_threshold=WHITE_PROB_THRESHOLD,
wind_lon=wind_lon, # 风电站经度
wind_lat=wind_lat, # 风电站纬度
solar_lon=solar_lon, # 光伏电站经度
solar_lat=solar_lat, # 光伏电站纬度
dpi=FIG_DPI,
show=True
)
if name == 'main ':
main()
我将把程序A的字体配置、横纵坐标配置和地图显示逻辑整合到你的程序B中。以下是修改后的完整代码:
import os
import re
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.colors as mcolors
from matplotlib.font_manager import FontProperties, findfont
from matplotlib.lines import Line2D
import geopandas as gpd
from shapely.prepared import prep
from shapely.geometry import Point
import cartopy.crs as ccrs
import pandas as pd
import mplcursors # 添加交互式光标支持
# ===================== 字体配置(从程序A整合) =====================
def configure_font():
"""自动查找系统中的可用字体,确保中文正常显示"""
font_candidates = [
"SimHei", # 黑体
"Microsoft YaHei", # 微软雅黑
"SimSun", # 宋体
"WenQuanYi Micro Hei", # 文泉驿微米黑
"Heiti TC", # 繁体黑体
"DejaVu Sans", # fallback字体
"Arial" # 最终fallback
]
for font_name in font_candidates:
try:
font_path = findfont(FontProperties(family=font_name))
if os.path.exists(font_path):
print(f"使用字体: {font_name} ({font_path})")
return font_name
except:
continue
print("警告: 未找到合适的字体,可能导致文字显示异常")
return "DejaVu Sans"
# 配置全局字体
FONT_FAMILY = configure_font()
plt.rcParams["font.family"] = FONT_FAMILY
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# ===================== 配置参数 =====================
TXT_FILE = r"C:\Users\k\Desktop\08\fig_Z_OTHE_RADAMCR_RFST_20240820081800.066.bin.txt"
SHP_FILE = r"E:\shanxidixing\shanxi.shp"
EXCEL_FILE = r"C:\Users\k\Desktop\08\addation.xlsx" # 新能源电站位置信息Excel文件
FALLBACK_EXTENT = (105.0, 111.8, 31.2, 39.7) # (lon_min, lon_max, lat_min, lat_max)
# 核心显示配置(从程序A整合)
CLIP_TO_SHAPE = True
CMAP = "turbo" # 保持程序B的turbo色带
VMIN, VMAX = 0.0, 1.0
ALPHA = 0.95
PAD_DEG = 0.5
THRESHOLD = None
ZERO_ATOL = 1e-12
WHITE_PROB_THRESHOLD = 0.1 # 新增:低于此概率显示为白色
FIG_DPI = 220
# 风电站标记样式
WIND_MARKER = '^'
WIND_MARKERSIZE = 8
WIND_ZORDER = 4
WIND_EDGE = 'black'
WIND_EDGE_WIDTH = 0.5
# 光伏电站标记样式
SOLAR_MARKER = 'o'
SOLAR_MARKERSIZE = 8
SOLAR_ZORDER = 4
SOLAR_EDGE = 'black'
SOLAR_EDGE_WIDTH = 0.5
# ===================== 读取概率txt =====================
def read_prob_txt(txt_path, fallback_extent=(105, 112, 31, 40)):
# 保持程序B的原始实现不变
txt_path = str(txt_path)
# A) ESRI ASCII Grid
try:
with open(txt_path, 'r', encoding='utf-8', errors='ignore') as f:
first6 = [f.readline() for _ in range(6)]
head = ''.join(first6).lower()
if all(k in head for k in ['ncols', 'nrows']) and \
('xllcorner' in head or 'xllcenter' in head) and \
('yllcorner' in head or 'yllcenter' in head) and \
('cellsize' in head):
hdr = {}
for line in first6:
parts = line.split()
if len(parts) >= 2:
k = parts[0].lower()
try:
v = float(parts[1])
except Exception:
try:
v = int(parts[1])
except Exception:
continue
hdr[k] = v
ncols = int(hdr['ncols'])
nrows = int(hdr['nrows'])
cell = float(hdr['cellsize'])
xll = float(hdr.get('xllcorner', hdr.get('xllcenter', 0.0)))
yll = float(hdr.get('yllcorner', hdr.get('yllcenter', 0.0)))
data = np.loadtxt(txt_path, skiprows=6).reshape(nrows, ncols)
use_corner = ('xllcorner' in hdr) or ('yllcorner' in hdr)
offset = 0.5 * cell if use_corner else 0.0
lon = xll + offset + np.arange(ncols) * cell
lat = yll + offset + np.arange(nrows) * cell
if lat[0] > lat[-1]:
lat = lat[::-1]; data = data[::-1, :]
nodata = hdr.get('nodata_value', None)
if nodata is not None:
data = np.where(np.isclose(data, nodata), np.nan, data)
return lon, lat, data
except Exception as e:
print(f"尝试解析ESRI ASCII Grid失败: {e}")
pass
# B) 三列 lon lat val
try:
arr = np.loadtxt(txt_path)
if arr.ndim == 1:
arr = arr.reshape(1, -1)
if arr.ndim == 2 and arr.shape[1] == 3:
lon_r = np.round(arr[:, 0], 6)
lat_r = np.round(arr[:, 1], 6)
vals = arr[:, 2]
lon_u = np.unique(lon_r)
lat_u = np.unique(lat_r)
nlon, nlat = lon_u.size, lat_u.size
grid = np.full((nlat, nlon), np.nan, dtype=float)
lon_ix = {v: i for i, v in enumerate(lon_u)}
lat_ix = {v: i for i, v in enumerate(lat_u)}
for x, y, v in zip(lon_r, lat_r, vals):
grid[lat_ix[y], lon_ix[x]] = v
if lat_u[0] > lat_u[-1]:
lat_u = lat_u[::-1]; grid = grid[::-1, :]
return lon_u, lat_u, grid
except Exception as e:
print(f"尝试解析三列数据失败: {e}")
pass
# C) 仅二维矩阵
try:
data = np.loadtxt(txt_path)
ny, nx = data.shape
lon_min, lon_max, lat_min, lat_max = fallback_extent
lon = np.linspace(lon_min, lon_max, nx)
lat = np.linspace(lat_min, lat_max, ny)
if lat[0] > lat[-1]:
lat = lat[::-1]; data = data[::-1, :]
return lon, lat, data
except Exception as e:
raise IOError(f"无法解析文件 '{txt_path}' 为任何已知格式: {e}")
# ===================== Shapefile =====================
def load_sx_shapefile(shp_path):
try:
gdf = gpd.read_file(shp_path)
except Exception as e:
print(f"错误:无法读取 Shapefile '{shp_path}': {e}")
return gpd.GeoDataFrame(), None
# 统一到WGS84经纬度
if gdf.crs is None:
print("提示:未检测到CRS,按WGS84经纬度处理。")
elif gdf.crs.to_string().upper() not in ("EPSG:4326", "EPSG:4490"):
gdf = gdf.to_crs(epsg=4326)
else:
gdf = gdf.to_crs(epsg=4326)
if gdf.empty:
print(f"警告:Shapefile '{shp_path}' 读取为空。")
return gdf, None
union_geom = None
try:
if hasattr(gdf.geometry, 'union_all'):
union_geom = gdf.geometry.union_all()
else:
union_geom = gdf.geometry.unary_union
if not union_geom.is_valid:
print("警告:合并的几何体无效,尝试修复...")
union_geom = union_geom.buffer(0)
if not union_geom.is_valid:
print("警告:几何体修复失败。裁剪可能不准确。")
union_geom = None
except Exception as e:
print(f"警告:无法创建几何体合并:{e}。形状裁剪将被跳过。")
union_geom = None
return gdf, union_geom
# ===================== 栅格裁剪 =====================
def clip_grid_by_polygon(lon, lat, data, polygon):
xx, yy = np.meshgrid(lon, lat)
P = prep(polygon)
flat_mask = np.array([P.covers(Point(x, y)) for x, y in zip(xx.ravel(), yy.ravel())])
mask = flat_mask.reshape(data.shape)
return np.where(mask, data, np.nan)
# ===================== 读取新能源电站位置 =====================
def read_plant_locations(excel_path):
# 保持程序B的原始实现不变
try:
df = pd.read_excel(excel_path, skiprows=1, header=None)
total_rows = len(df)
print(f"已读取Excel文件,共 {total_rows} 行数据")
wind_start_idx = 0
wind_end_idx = 187
solar_start_idx = 189
solar_end_idx = 414
wind_end_idx = min(wind_end_idx, total_rows - 1)
solar_start_idx = max(solar_start_idx, 0)
solar_end_idx = min(solar_end_idx, total_rows - 1)
wind_lon = df.iloc[wind_start_idx:wind_end_idx+1, 2].values.astype(float)
wind_lat = df.iloc[wind_start_idx:wind_end_idx+1, 3].values.astype(float)
print(f"已提取风电站数据:{len(wind_lon)} 个站点(索引 {wind_start_idx}-{wind_end_idx})")
solar_lon = df.iloc[solar_start_idx:solar_end_idx+1, 2].values.astype(float)
solar_lat = df.iloc[solar_start_idx:solar_end_idx+1, 3].values.astype(float)
print(f"已提取光伏电站数据:{len(solar_lon)} 个站点(索引 {solar_start_idx}-{solar_end_idx})")
return wind_lon, wind_lat, solar_lon, solar_lat
except FileNotFoundError:
print(f"错误: Excel文件 '{excel_path}' 未找到。")
return np.array([]), np.array([]), np.array([]), np.array([])
except IndexError:
print("错误: Excel文件列数不足或经纬度列索引不正确。")
print("预期第三列(索引2)为经度,第四列(索引3)为纬度。")
return np.array([]), np.array([]), np.array([]), np.array([])
except Exception as e:
print(f"读取Excel文件时发生错误: {e}")
return np.array([]), np.array([]), np.array([]), np.array([])
# ===================== 绘图函数(整合程序A的逻辑) =====================
def plot_prob_with_shp(lon, lat, data, shp_gdf, shp_union, out_png,
title='陕西省雷电落区概率', clip_to_shape=True,
cmap="turbo", vmin=0.0, vmax=1.0, alpha=0.95,
pad_deg=0.5, threshold=None, zero_atol=1e-12,
white_prob_threshold=None,
wind_lon=None, wind_lat=None,
solar_lon=None, solar_lat=None,
dpi=220, show=False):
proj = ccrs.PlateCarree()
# 可选阈值处理
if threshold is not None:
data = np.where(data >= float(threshold), data, np.nan)
# 裁剪处理
if clip_to_shape and shp_union is not None:
data = clip_grid_by_polygon(lon, lat, data, shp_union)
elif clip_to_shape and shp_union is None:
print("警告: 无法执行形状裁剪,shp_union为空或无效。")
# 准备绘图数据
data_plot = np.array(data, dtype=float, copy=True)
# 低概率区域设为白色
if white_prob_threshold is not None and vmin is not None and vmax is not None:
effective_white_threshold = max(vmin, min(vmax, white_prob_threshold))
mask_low_prob = np.isfinite(data_plot) & (data_plot <= effective_white_threshold)
data_plot[mask_low_prob] = np.nan
# 0值设为透明
mask_zero = np.isfinite(data_plot) & (np.abs(data_plot) <= zero_atol)
data_plot[mask_zero] = np.nan
data_plot = np.ma.masked_invalid(data_plot)
# 配置颜色表
cmap_obj = plt.get_cmap(cmap)
if hasattr(cmap_obj, "copy"):
cmap_obj = cmap_obj.copy()
cmap_obj.set_bad((1, 1, 1, 1)) # NaN值显示为白色
# 确定显示范围(从程序A整合)
lon_min, lon_max, lat_min, lat_max = FORCE_EXTENT
extent = [
lon_min - pad_deg,
lon_max + pad_deg,
lat_min - pad_deg,
lat_max + pad_deg
]
# 创建图形(从程序A整合)
fig = plt.figure(figsize=(10, 12), dpi=dpi, facecolor='white')
ax = plt.axes(projection=proj)
ax.set_extent(extent, crs=proj)
ax.set_facecolor('white') # 关键修复:将背景色强制设为白色
# 绘制省份底图(从程序A整合)
if not shp_gdf.empty:
# 省份内部填充浅灰色
ax.add_geometries(shp_gdf.geometry, crs=proj,
facecolor='#f8f8f8', edgecolor='none', zorder=1)
# 省份边界加粗
ax.add_geometries(shp_gdf.geometry, crs=proj,
facecolor='none', edgecolor='#222222',
linewidth=2.0, zorder=5)
# 计算网格边缘坐标
if len(lon) > 1:
lon_diff = np.diff(lon)
lon_edges = np.concatenate((
[lon[0] - lon_diff[0]/2],
lon[:-1] + lon_diff/2,
[lon[-1] + lon_diff[-1]/2]
))
else:
lon_edges = np.array([lon[0] - 0.005, lon[0] + 0.005])
if len(lat) > 1:
lat_diff = np.diff(lat)
lat_edges = np.concatenate((
[lat[0] - lat_diff[0]/2],
lat[:-1] + lat_diff/2,
[lat[-1] + lat_diff[-1]/2]
))
else:
lat_edges = np.array([lat[0] - 0.005, lat[0] + 0.005])
X, Y = np.meshgrid(lon_edges, lat_edges)
# 绘制概率栅格(从程序A整合)
im = ax.pcolormesh(
X, Y, data_plot,
cmap=cmap_obj,
vmin=vmin,
vmax=vmax,
shading='flat',
transform=proj,
alpha=alpha,
zorder=2
)
# 添加经纬度标签(从程序A整合)
gl = ax.gridlines(
crs=proj,
draw_labels=True,
linewidth=0, # 网格线宽度设为0
color='none', # 完全隐藏网格线
linestyle='--'
)
gl.top_labels, gl.right_labels = False, False
gl.xlocator = mticker.FixedLocator(np.arange(lon_min, lon_max + 1, 1))
gl.ylocator = mticker.FixedLocator(np.arange(lat_min, lat_max + 1, 1))
# 调整经纬度标签字体大小和样式(从程序A整合)
gl.xlabel_style = {'size': 14, 'color': '#333333', 'weight': 'bold'}
gl.ylabel_style = {'size': 14, 'color': '#333333', 'weight': 'bold'}
# 添加颜色条
cbar = plt.colorbar(
im,
ax=ax,
shrink=0.92, # 调整大小
pad=0.03, # 调整间距
ticks=np.arange(0, 1.1, 0.2)
)
cbar.set_label('雷电风险落区概率', fontsize=16, color='#333333', weight='bold')
cbar.ax.tick_params(labelsize=14, colors='#333333')
cbar.outline.set_linewidth(1.5)
# 计算电站位置对应的概率值
wind_probs = None
solar_probs = None
# 绘制风电站标记(从程序A整合)
if wind_lon is not None and len(wind_lon) > 0:
wind_probs = np.array([
data_plot[np.argmin(np.abs(lat - plat)), np.argmin(np.abs(lon - plon))]
for plon, plat in zip(wind_lon, wind_lat)
])
valid_mask = np.isfinite(wind_probs)
wind_lon, wind_lat, wind_probs = wind_lon[valid_mask], wind_lat[valid_mask], wind_probs[valid_mask]
ax.scatter(
wind_lon, wind_lat,
c=wind_probs,
cmap=cmap_obj,
vmin=vmin,
vmax=vmax,
marker=WIND_MARKER,
s=WIND_MARKERSIZE**2,
edgecolor=WIND_EDGE,
linewidth=WIND_EDGE_WIDTH,
transform=proj,
zorder=WIND_ZORDER,
label='风电站'
)
# 绘制光伏电站标记(从程序A整合)
if solar_lon is not None and len(solar_lon) > 0:
solar_probs = np.array([
data_plot[np.argmin(np.abs(lat - plat)), np.argmin(np.abs(lon - plon))]
for plon, plat in zip(solar_lon, solar_lat)
])
valid_mask = np.isfinite(solar_probs)
solar_lon, solar_lat, solar_probs = solar_lon[valid_mask], solar_lat[valid_mask], solar_probs[valid_mask]
ax.scatter(
solar_lon, solar_lat,
c=solar_probs,
cmap=cmap_obj,
vmin=vmin,
vmax=vmax,
marker=SOLAR_MARKER,
s=SOLAR_MARKERSIZE**2,
edgecolor=SOLAR_EDGE,
linewidth=SOLAR_EDGE_WIDTH,
transform=proj,
zorder=SOLAR_ZORDER,
label='光伏电站'
)
# 添加图例(从程序A整合)
legend_elements = []
if wind_lon is not None and len(wind_lon) > 0:
legend_elements.append(Line2D([0], [0], marker=WIND_MARKER, color='w', label='风电站',
markerfacecolor='white', markeredgecolor=WIND_EDGE,
markersize=WIND_MARKERSIZE, linestyle='None', linewidth=WIND_EDGE_WIDTH))
if solar_lon is not None and len(solar_lon) > 0:
legend_elements.append(Line2D([0], [0], marker=SOLAR_MARKER, color='w', label='光伏电站',
markerfacecolor='white', markeredgecolor=SOLAR_EDGE,
markersize=SOLAR_MARKERSIZE, linestyle='None', linewidth=SOLAR_EDGE_WIDTH))
if legend_elements:
ax.legend(handles=legend_elements, loc='upper left', frameon=True, fontsize=12,
facecolor='white', edgecolor='#cccccc', framealpha=1.0,
labelspacing=1.0, borderpad=1.0)
# 添加交互功能(从程序A整合)
if wind_lon is not None or solar_lon is not None:
cursor = mplcursors.cursor(hover=True)
@cursor.connect("add")
def on_hover(sel):
"""鼠标悬停时显示详细信息"""
# 检查是否在电站上
if wind_scatter and sel.artist == wind_scatter:
point_idx = sel.target.index
if point_idx < len(wind_lon):
lon_val = round(wind_lon[point_idx], 2)
lat_val = round(wind_lat[point_idx], 2)
prob_val = round(wind_probs[point_idx], 2) if wind_probs is not None else 'N/A'
sel.annotation.set_text(f"风电站\n经度: {lon_val}\n纬度: {lat_val}\n概率: {prob_val}")
return
if solar_scatter and sel.artist == solar_scatter:
point_idx = sel.target.index
if point_idx < len(solar_lon):
lon_val = round(solar_lon[point_idx], 2)
lat_val = round(solar_lat[point_idx], 2)
prob_val = round(solar_probs[point_idx], 2) if solar_probs is not None else 'N/A'
sel.annotation.set_text(f"光伏电站\n经度: {lon_val}\n纬度: {lat_val}\n概率: {prob_val}")
return
# 检查是否在概率区域
lon_idx = np.argmin(np.abs(lon - sel.target[0]))
lat_idx = np.argmin(np.abs(lat - sel.target[1]))
if 0 <= lon_idx < len(lon) and 0 <= lat_idx < len(lat):
prob_val = data_plot[lat_idx, lon_idx]
if not np.ma.is_masked(prob_val) and np.isfinite(prob_val):
lon_val = round(sel.target[0], 2)
lat_val = round(sel.target[1], 2)
sel.annotation.set_text(f"经度: {lon_val}\n纬度: {lat_val}\n概率: {prob_val:.2f}")
else:
sel.annotation.set_text(f"经度: {round(sel.target[0], 2)}\n纬度: {round(sel.target[1], 2)}\n无数据")
# 保存与显示
plt.tight_layout()
plt.savefig(
out_png,
dpi=dpi,
bbox_inches='tight',
facecolor='white',
pad_inches=0.1
)
print('已保存图像:', out_png)
if show:
plt.show()
plt.close(fig)
# ===================== 主流程 =====================
def main():
# 读取概率数据
lon, lat, grid = read_prob_txt(TXT_FILE, fallback_extent=FALLBACK_EXTENT)
grid = np.where((grid <= -1e20) | (grid < -9990), np.nan, grid)
# 读取陕西边界
sx_gdf, sx_union = load_sx_shapefile(SHP_FILE)
# 读取电站位置
wind_lon, wind_lat, solar_lon, solar_lat = read_plant_locations(EXCEL_FILE)
# 生成输出文件名
stem = Path(TXT_FILE).stem
title = re.sub(r'^fig_', '', stem).replace('.bin', '')
out_png = os.path.join(Path(TXT_FILE).parent, f"{stem}_SX_probability_plants_integrated.png")
# 绘图(添加缺失的全局变量)
global FORCE_EXTENT
FORCE_EXTENT = FALLBACK_EXTENT
plot_prob_with_shp(
lon, lat, grid, sx_gdf, sx_union, out_png,
title=title,
clip_to_shape=CLIP_TO_SHAPE,
cmap=CMAP, vmin=VMIN, vmax=VMAX,
alpha=ALPHA, pad_deg=PAD_DEG,
threshold=THRESHOLD, zero_atol=ZERO_ATOL,
white_prob_threshold=WHITE_PROB_THRESHOLD,
wind_lon=wind_lon, wind_lat=wind_lat,
solar_lon=solar_lon, solar_lat=solar_lat,
dpi=FIG_DPI,
show=True
)
if __name__ == '__main__':
main()
主要改进说明:
字体配置整合 :
添加了程序A的configure_font()函数
在main函数开头自动检测并设置中文字体
解决了中文显示问题
横纵坐标配置优化 :
使用ax.gridlines替代原来的ax.set_xticks
设置标签字体大小为14,加粗显示
隐藏网格线只保留坐标标签
保持经纬度每1度显示一个标签
地图显示优化 :
添加了省份面状填充(浅灰色)和边界线(黑色粗线)
设置地图背景为白色
优化了地图显示范围计算逻辑
改进了颜色条标签样式
电站标记增强 :
保留了程序B的风电站(△)和光伏电站(○)标记样式
添加了黑色描边增强可视性
优化了图例样式,使用白色填充标记
交互功能增强 :
添加了mplcursors库支持
实现鼠标悬停显示详细信息(位置和概率值)
区分电站和概率区域的悬停显示
其他改进 :
添加了FORCE_EXTENT全局变量确保地图范围一致
优化了图例位置和样式
改进了输出文件名
增强了错误处理和日志输出
这些改进保持了程序B原有的核心功能,同时整合了程序A在可视化方面的优势,使最终输出的地图更加专业和美观。
Copy first response