本文档旨在指导读者使用 Matplotlib 绘制圆形温度热图。针对数据稀疏导致的热图形状失真问题,我们将介绍如何通过添加角点数据来改善插值效果,从而获得更准确的圆形温度分布可视化结果。内容涵盖数据准备、插值算法选择、圆形遮罩应用以及自定义颜色映射等关键步骤,助您轻松创建专业的热图。
首先,我们需要准备包含坐标 (x, y) 和温度值的 CSV 数据文件。 确保数据格式正确,例如:
| x | y | temp| | -140 | 0 | 397.32 | | -100 | 90 | 396.76 | | -100 | -90 | 396.34 | | -70 | 0 | 396 | | -50 | 44 | 395.34 | | -50 | -44 | 395.57 | | 0 | 140 | 396.37 | | 0 | 70 | 395.82 | | 0 | 0 | 393.52 | | 0 | -70 | 393.52 | | 0 | -140 | 395.61| | 50 | 44 | 395.82 | | 50 | -44 | 394.08 | | 50 | -44 | 394.08 | | 70 | 0 | 394.62 | | 100 | 90 | 395.79 | | 100 | -90 | 395.25 | | 140 | 0 | 396.12 |
关键步骤: 为了解决热图呈现八边形而非圆形的问题,我们需要在数据集中添加位于图像四个角点的数据。 这有助于插值算法在整个区域内生成更准确的温度分布。 例如,可以添加以下数据:
| x | y | temp| | -150 | -150 | 398 | | 150 | 150 | 398 | | 150 | -150 | 398 | | -150 | 150 | 398 |
请根据实际情况调整角点温度值。
以下是使用 Matplotlib 绘制圆形温度热图的完整代码:
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import griddata from matplotlib.colors import LinearSegmentedColormap # Load temperature data from CSV file file_path = 'tcdata.csv' data = pd.read_csv(file_path) # Extract coordinates and temperatures from the data x = data['x'] y = data['y'] temperatures = data['temp'] # Set the radius for the circle radius = 150 # Create a grid for interpolation grid_x, grid_y = np.mgrid[-radius:radius:300j, -radius:radius:300j] # Interpolate the temperature data over the grid grid_temperatures = griddata((x, y), temperatures, (grid_x, grid_y), method='cubic') # Create a circular mask to limit the heatmap within the circle mask = np.sqrt(grid_x**2 + grid_y**2) > radius grid_temperatures = np.ma.masked_where(mask, grid_temperatures) # Create a custom color map: blue for the lowest, red for the highest, and green for intermediate temperatures cmap = LinearSegmentedColormap.from_list('custom_heatmap', ['blue', 'green', 'red'], N=256) # Plot the heatmap plt.figure(figsize=(8, 6)) plt.imshow(grid_temperatures.T, extent=(-radius, radius, -radius, radius), origin='lower', cmap=cmap) plt.colorbar(label='Temperature (°C)') # Set the title plt.title('Circular Temperature Distribution Heatmap') # Disable the grid plt.grid(False) # Display the plot plt.show()
代码详解:
通过添加角点数据并使用适当的插值方法,我们可以使用 Matplotlib 绘制出更准确、更美观的圆形温度热图。 本教程提供了一个基本框架,您可以根据实际需求进行修改和扩展,例如添加等高线、调整颜色映射、以及集成到更复杂的分析流程中。
以上就是使用 Matplotlib 绘制圆形温度热图:插值与优化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号