因学习需要绘制等值线图,使用Python简单写了个程序,程序通过excel读取表格数据,绘制图形后将图片保存到本地,希望可以帮到有需要的你!
# 导入必要的库
import pandas as pd # 用于处理Excel数据
import numpy as np # 用于数值计算
import matplotlib.pyplot as plt # 用于绘图
import os
from datetime import datetime # 导入datetime模块
from scipy.interpolate import griddata
# 创建输出文件夹
output_folder = 'output'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 获取当前时间并生成时间戳
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
print(f"开始读取数据...")
# 从 Excel 文件中读取数据
file_path = 'data.xlsx' # Excel 文件的路径
df = pd.read_excel(file_path) # 读取 Excel 文件
print(f"数据处理中...")
# 获取 X, Y, Z 数据
x = df['X'].values # 获取 X 列数据
y = df['Y'].values # 获取 Y 列数据
z = df['Z'].values # 获取 Z 列数据
labels = df['N'].values # 获取井号列作为标识
# 创建网格点
grid_x, grid_y = np.meshgrid(np.linspace(min(x), max(x), 100), np.linspace(min(y), max(y), 100))
# 使用 griddata 对 Z 值进行插值,使其在网格上生成平滑的等值线
grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic')
print(f"绘制图表中...")
# 创建一个绘图对象
plt.figure()
# 翻转 Y 轴(保留原始 y 值,但翻转显示顺序)
plt.gca().invert_yaxis()
# 绘制等值线图
contour = plt.contour(grid_x, grid_y, grid_z, levels=10, cmap='viridis')
# 添加等值线标签
plt.clabel(contour, inline=True, fontsize=8)
# 设置 X 轴在顶部
plt.gca().xaxis.set_label_position('top') # 将 X 轴标签放在顶部
plt.gca().xaxis.tick_top() # 将 X 轴刻度放在顶部
# 控制 X 轴从 0 或某个特定值开始
plt.xlim(left=0) # 将 X 轴从 0 开始
plt.xlim(right=6000)
# 在图中标记数据点
plt.scatter(x, y, color='red', label='Data Points') # 标记数据点为红色
# 添加每个点的标识(井号)
for i in range(len(x)):
plt.text(x[i], y[i], labels[i], fontsize=9, ha='right', va='bottom', color='blue') # 在点旁边显示井号
# 显示网格线
plt.grid(True, which='both', linestyle='--', linewidth=0.5, color='gray')
# 添加标题和标签
plt.suptitle('Contour Map', y=0.1) # 将标题放在底部
plt.xlabel('X-axis') # X 轴标签在顶部
plt.ylabel('Y-axis')
# 显示颜色条
plt.colorbar(contour)
# 显示图例
plt.legend()
# 使用时间戳命名文件
file_name = f'{output_folder}/img_{timestamp}.png'
print(f"运行结束!")
# 保存图片
plt.savefig(file_name, dpi=300)
# 输出图片路径
print(f"图像已保存为: {file_name}")
# 显示绘制的图像
plt.show()
效果图如下:
同时,我还生成了WIN下课执行性的exe文件,无需Python环境也可以运行