LXX
读完需要
速读仅需 1 分钟
前言:
最近在上网查资料(摸鱼)的时候看到一幅很有意思的图,本文简单地复现一下。
1
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox, TransformedBbox, blended_transform_factory
from mpl_toolkits.axes_grid1.inset_locator import BboxPatch, BboxConnector
import imageio
import rasterio
# 从 GeoTIFF 中读取 NDVI 数据
tif_file_path = "C:/Users/LXX/Downloads/NDVI.tif" # 请将路径替换为你的 NDVI 影像文件路径
with rasterio.open(tif_file_path) as src:
ndvi_data = src.read(1) # 假设 NDVI 数据在第一个波段
ndvi_transform = src.transform
# 获取 NDVI 图像的范围
height, width = ndvi_data.shape
distance = np.arange(width)
depth = np.arange(height)
# 创建缩放效果的函数
def zoom_effect(ax1, ax2, xmin, xmax, **kwargs):
trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)
trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)
bbox = Bbox.from_extents(xmin, 0, xmax, 1)
mybbox1 = TransformedBbox(bbox, trans1)
mybbox2 = TransformedBbox(bbox, trans2)
c1 = BboxConnector(mybbox1, mybbox2, loc1=3, loc2=3, **kwargs)
c1.set_clip_on(False)
c2 = BboxConnector(mybbox1, mybbox2, loc1=4, loc2=4, **kwargs)
c2.set_clip_on(False)
bbox_patch1 = BboxPatch(mybbox1, facecolor='none', edgecolor='red', linewidth=1.5)
bbox_patch2 = BboxPatch(mybbox2, facecolor='none', edgecolor='red', linewidth=1.5)
ax1.add_patch(bbox_patch1)
ax2.add_patch(bbox_patch2)
ax1.add_patch(c1)
ax1.add_patch(c2)
# 创建主轴和缩放区域的函数
def create_zoomed_plot(frame_num):
xmin = frame_num * 10
xmax = min((frame_num + 10) * 10 + 150, width)
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(8, 10), gridspec_kw={'height_ratios': [5, 1]})
mesh1 = ax1.imshow(ndvi_data, aspect='auto', cmap='jet', origin='lower', extent=[0, width, 0, height])
ax1.set_ylabel('Pixel Index (height)')
ax1.set_title('NDVI Zoomed Analysis')
cbar1 = fig.colorbar(mesh1, ax=ax1, orientation='vertical', pad=0.01)
cbar1.set_label('NDVI')
mesh2 = ax2.imshow(ndvi_data[:, xmin:xmax], aspect='auto', cmap='jet', origin='lower', extent=[xmin, xmax, 0, height])
ax2.set_ylabel('Pixel Index (height)')
ax2.set_xlabel('Pixel Index (width)')
zoom_effect(ax1, ax2, xmin, xmax, edgecolor='red', linewidth=1.5)
fig.tight_layout()
plt.savefig(f"frame_{frame_num:02d}.png", bbox_inches='tight')
plt.close(fig)
# 保存多个帧
for i in range(10):
create_zoomed_plot(i)
# 使用 imageio 生成 GIF
with imageio.get_writer('ndvi_movie_zoomed.gif', mode='I', fps=1) as writer:
for i in range(10):
filename = f"frame_{i:02d}.png"
image = imageio.imread(filename)
writer.append_data(image)
print("GIF 生成完成")
3
散点图(Scatter plot)是一种统计图表,一种数据可视化工具,用于显示两个变量之间的关系。 它通过在坐标平面上绘制数据点来展示变量之间的关联程度。
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# 创建随机数
n = 1000
x = np.random.uniform(20, 160, n)
y = 0.82 * x + 7.68 + np.random.normal(0, 10, n)
# 计算线性拟合
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
fit_line = slope * x + intercept
# 计算均方误差 (MSE)、根均方误差 (RMSE) 和平均绝对误差 (MAE)
mse = np.mean((y - fit_line) ** 2)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(y - fit_line))
# 绘制带拟合线的散点图
plt.figure(figsize=(8, 6))
scatter = plt.scatter(x, y,marker='.',c=y, cmap='magma', alpha=1, label='采样点')
plt.plot(x, fit_line, color='red', label=f'y={slope:.2f}x+{intercept:.2f}')
plt.plot([20, 180], [20, 180], '--', color='grey', label='y=x')
plt.rcParams['font.sans-serif'] = ['STSong']
plt.rcParams['axes.unicode_minus'] = False
# 计算95%置信区间
#confidence_interval = 1.96 * std_err
#upper_fit_line = fit_line + confidence_interval
#lower_fit_line = fit_line - confidence_interval
#plt.plot(x, upper_fit_line, 'k-', alpha=0.6)
#plt.plot(x, lower_fit_line, 'k-', alpha=0.6)
# 添加注释
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc='upper left')
plt.text(25, 125, f'$R^2$={r_value**2:.2f}, $P$<0.001\nMAE={mae:.2f}\nRMSE={rmse:.2f}\nMAPE={np.mean(np.abs((y - fit_line) / y)):.2f}', fontsize=12)
plt.xlim(20, 180)
plt.ylim(20, 180)
plt.show()