福衛七號:多個檔案分析
(使用Python)

福衛七號的大氣觀測資料

import os

import netCDF4 as nc

import csv


# 資料夾路徑

folde
r_path = r"C:\fs7data\fs7_2024065"


# CSV 檔案路徑

output_csv = r"C:\fs7data\results.csv"


# 開啟 CSV 檔案,設置寫入模式,並設置 CSV 寫入器

with open(output_csv, mode='w', newline='') as csvfile:

    fieldnames = ['File', 'Min_Temperature', 'Corresponding_Height', 'Corresponding_Latitude', 'Corresponding_Longitude']

    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)


    # 寫入 CSV 標題行

    writer.writeheader()


    # 取得資料夾中所有檔案

    file_list = os.listdir(folder_path)


    # 迭代處理每個檔案

    for file_name in file_list:

        if file_name.endswith('_nc'):  # 確認檔案是 NetCDF 檔案

            file_path = os.path.join(folder_path, file_name)

            

            # 開啟 NetCDF 檔案

            dataset = nc.Dataset(file_path, 'r')


            try:

                # 讀取溫度(Temp)、高度(MSL_alt)、經度(lat)、緯度(lon)資料

                temp = dataset.variables['Temp'][:]

                msl_alt = dataset.variables['MSL_alt'][:]

                lat = dataset.variables['lat'][:]

                lon = dataset.variables['lon'][:]


                # 找出溫度最低處的索引

                min_temp_index = temp.argmin()

                

                # 取得溫度最低處的溫度、高度、經度、緯度資料

                min_temp = temp[min_temp_index]

                corresponding_msl_alt = msl_alt[min_temp_index]

                corresponding_lat = lat[min_temp_index]

                corresponding_lon = lon[min_temp_index]


                # 寫入 CSV 檔案

                writer.writerow({

                    'File': file_name,

                    'Min_Temperature': min_temp,

                    'Corresponding_Height': corresponding_msl_alt,

                    'Corresponding_Latitude': corresponding_lat,

                    'Corresponding_Longitude': corresponding_lon

                })

            

            except KeyError as e:

                #print(f"檔案 '{file_name}' 中找不到所需的變數: {e}")


            finally:

                # 關閉 NetCDF 檔案

                dataset.close()



import csv  # 導入csv模組


# 設定檔案路徑

file_path = r"C:\fs7data\results.csv"


# 讀取 CSV 檔案並顯示內容

with open(file_path, mode='r', newline='') as csvfile:

    reader = csv.reader(csvfile)

    for row in reader:

        print(', '.join(row))



import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import pandas as pd


# 設定 CSV 檔案路徑

file_path = r"C:\fs7data\results.csv"


# 讀取 CSV 檔案為 DataFrame

df = pd.read_csv(file_path)


# 提取資料

heights = df['Corresponding_Height']

latitudes = df['Corresponding_Latitude']

longitudes = df['Corresponding_Longitude']

temperatures = df['Min_Temperature']


# 篩選符合範圍的數據

mask_longitude = (longitudes >= -180) & (longitudes <= 180)

mask_latitude = (latitudes >= -90) & (latitudes <= 90)


filtered_heights = heights[mask_longitude & mask_latitude]

filtered_latitudes = latitudes[mask_longitude & mask_latitude]

filtered_longitudes = longitudes[mask_longitude & mask_latitude]

filtered_temperatures = temperatures[mask_longitude & mask_latitude]


# 繪製3D圖形

fig = plt.figure(figsize=(10, 8))

ax = fig.add_subplot(111, projection='3d')


# 設置圖形標題和座標軸標籤

ax.set_title('Min Temperature Distribution')

ax.set_xlabel('Corresponding Latitude')

ax.set_ylabel('Corresponding Longitude')

ax.set_zlabel('Corresponding Height')


# 繪製3D散點圖,顏色以溫度資料呈現

sc = ax.scatter(filtered_latitudes, filtered_longitudes, filtered_heights,

                c=filtered_temperatures, cmap='coolwarm', marker='o')


# 添加色條

cbar = fig.colorbar(sc)

cbar.set_label('Min Temperature')


plt.show()



import matplotlib.pyplot as plt

import pandas as pd


# 設定 CSV 檔案路徑

file_path = r"C:\fs7data\results.csv"


# 讀取 CSV 檔案為 DataFrame

df = pd.read_csv(file_path)


# 提取資料

heights = df['Corresponding_Height']

latitudes = df['Corresponding_Latitude']

longitudes = df['Corresponding_Longitude']

temperatures = df['Min_Temperature']


# 篩選符合範圍的數據

mask_longitude = (longitudes >= -180) & (longitudes <= 180)

mask_latitude = (latitudes >= -90) & (latitudes <= 90)


filtered_latitudes = latitudes[mask_longitude & mask_latitude]

filtered_longitudes = longitudes[mask_longitude & mask_latitude]

filtered_heights = heights[mask_longitude & mask_latitude]

filtered_temperatures = temperatures[mask_longitude & mask_latitude]


# 繪製平面圖

plt.figure(figsize=(10, 8))

scatter = plt.scatter(filtered_longitudes, filtered_latitudes, c=filtered_heights, cmap='viridis', marker='o')


# 設置圖形標題和軸標籤

plt.title('Latitude vs Longitude with Height Colormap')

plt.xlabel('Corresponding Longitude')

plt.ylabel('Corresponding Latitude')


# 添加色條

cbar = plt.colorbar(scatter)

cbar.set_label('Corresponding Height')


plt.grid(True)

plt.show()



import matplotlib.pyplot as plt

import numpy as np

from scipy.interpolate import griddata

import pandas as pd


# 設定 CSV 檔案路徑

file_path = r"C:\fs7data\results.csv"


# 讀取 CSV 檔案為 DataFrame

df = pd.read_csv(file_path)


# 提取資料

heights = df['Corresponding_Height']

latitudes = df['Corresponding_Latitude']

longitudes = df['Corresponding_Longitude']

temperatures = df['Min_Temperature']


# 篩選符合範圍的數據

mask_longitude = (longitudes >= -180) & (longitudes <= 180)

mask_latitude = (latitudes >= -90) & (latitudes <= 90)


filtered_latitudes = latitudes[mask_longitude & mask_latitude]

filtered_longitudes = longitudes[mask_longitude & mask_latitude]

filtered_heights = heights[mask_longitude & mask_latitude]


# 設置格點網格

x = np.linspace(min(filtered_longitudes), max(filtered_longitudes), 100)

y = np.linspace(min(filtered_latitudes), max(filtered_latitudes), 100)

X, Y = np.meshgrid(x, y)


# 內插溫度資料

Z = griddata((filtered_longitudes, filtered_latitudes), filtered_heights, (X, Y), method='linear')


# 繪製填滿的等高線圖

plt.figure(figsize=(10, 8))

plt.tripcolor(X.flatten(), Y.flatten(), Z.flatten(), cmap='viridis', shading='gouraud')


# 設置圖形標題和軸標籤

plt.title('Interpolated Filled Contour Plot')

plt.xlabel('Corresponding Longitude')

plt.ylabel('Corresponding Latitude')


# 添加色條

plt.colorbar(label='Corresponding Height')


plt.grid(True)

plt.show()



下載簡易的海岸線向量檔,並儲存在"C:\fs7data\ne_110m_coastline"資料夾中
https://www.naturalearthdata.com/downloads/110m-physical-vectors/

安裝geopandas 和 cartopy函式庫


pip install geopandas cartopy

import matplotlib.pyplot as plt

import numpy as np

from scipy.interpolate import griddata

import pandas as pd

import geopandas as gpd

import cartopy.crs as ccrs

import cartopy.feature as cfeature


# 設定 CSV 檔案路徑

file_path = r"C:\fs7data\results.csv"


# 讀取 CSV 檔案為 DataFrame

df = pd.read_csv(file_path)


# 提取資料

heights = df['Corresponding_Height']

latitudes = df['Corresponding_Latitude']

longitudes = df['Corresponding_Longitude']

temperatures = df['Min_Temperature']


# 篩選符合範圍的數據

mask_longitude = (longitudes >= -180) & (longitudes <= 180)

mask_latitude = (latitudes >= -90) & (latitudes <= 90)


filtered_latitudes = latitudes[mask_longitude & mask_latitude]

filtered_longitudes = longitudes[mask_longitude & mask_latitude]

filtered_heights = heights[mask_longitude & mask_latitude]


# 設置格點網格

x = np.linspace(min(filtered_longitudes), max(filtered_longitudes), 100)

y = np.linspace(min(filtered_latitudes), max(filtered_latitudes), 100)

X, Y = np.meshgrid(x, y)


# 內插溫度資料

Z = griddata((filtered_longitudes, filtered_latitudes), filtered_heights, (X, Y), method='linear')


# 創建圖形和軸

fig = plt.figure(figsize=(12, 8))

ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())


# 添加填滿的等高線圖

img = ax.tripcolor(X.flatten(), Y.flatten(), Z.flatten(), cmap='viridis', transform=ccrs.PlateCarree())


# 添加海岸線

coastline = gpd.read_file(r'C:\fs7data\ne_110m_coastline.shp')

ax.add_feature(cfeature.COASTLINE.with_scale('110m'), linewidth=0.5, edgecolor='black')


# 設置圖例

cbar = fig.colorbar(img, ax=ax, orientation='vertical', shrink=0.7, pad=0.05)

cbar.set_label('Corresponding Height', fontsize=12)


# 設置地圖邊界和標題

ax.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())

ax.set_title('Interpolated Filled Contour Plot with Coastlines', fontsize=16)


# 顯示圖形

plt.tight_layout()

plt.show()



import pandas as pd

import matplotlib.pyplot as plt

import cartopy.crs as ccrs

from cartopy.feature import NaturalEarthFeature


# Read data from CSV

file_path = r'C:\fs7data\results.csv'

df = pd.read_csv(file_path)


# Extract data

lats = df['Corresponding_Latitude']

lons = df['Corresponding_Longitude']

temps = df['Min_Temperature']


# Create a figure and axis with Cartopy projection

fig, ax = plt.subplots(figsize=(12, 8), subplot_kw={'projection': ccrs.PlateCarree()})


# Add coastline feature

coastline = NaturalEarthFeature(category='physical', name='coastline', scale='110m', edgecolor='black', facecolor='none')

ax.add_feature(coastline, linewidth=0.5)


# Scatter plot with temperature as color

sc = ax.scatter(lons, lats, c=temps, cmap='coolwarm', s=50, marker='o', alpha=0.7, edgecolors='k', linewidth=0.5)


# Colorbar

cbar = plt.colorbar(sc)

cbar.set_label('Min Temperature (°C)')


# Labels and title

ax.set_xlabel('Longitude')

ax.set_ylabel('Latitude')

ax.set_title('Min Temperature Distribution over Corresponding Coordinates')


# Show plot

plt.show()