|
| 1 | +import cfplot as cfp |
| 2 | +import cf |
| 3 | +import numpy as np |
| 4 | +import pandas as pd |
| 5 | +from datetime import timedelta |
| 6 | +import matplotlib.pyplot as plt |
| 7 | + |
| 8 | +# 1. Load the dataset |
| 9 | +file_path = "~/Documents/Datasets/ERA5_monthly_averaged_SST.nc" |
| 10 | +f = cf.read(file_path) |
| 11 | +sst = f[0] # Select the SST variable |
| 12 | + |
| 13 | +# Collapse data by area mean (average over spatial dimensions) |
| 14 | +am = sst.collapse("area: mean") # equivalent to "X Y: mean" |
| 15 | +am.squeeze(inplace=True) |
| 16 | + |
| 17 | +# Check available coordinates (already found 'dimensioncoordinate0' as the time coordinate) |
| 18 | +print("Available coordinates:", am.coordinates()) |
| 19 | + |
| 20 | +am_data_key = am.coordinate("dimensioncoordinate0", key=True) |
| 21 | +am_copy = am.copy().subspace(**{am_data_key: cf.mam()}) |
| 22 | +print(am_copy) |
| 23 | +exit() |
| 24 | +# Retrieve the time coordinate using its internal identifier |
| 25 | +am_data = am.coordinate("dimensioncoordinate0") |
| 26 | +am_data_copy = am_copy.coordinate("dimensioncoordinate0") |
| 27 | +# Convert the time data from 'hours since 1900-01-01' to datetime format |
| 28 | +#time_units = time_coord.units |
| 29 | +#am_time = time_coord.data |
| 30 | +#am_time_datetime = am.subspace(T=cf.dt("2022-12-01 00:00:00")) |
| 31 | + |
| 32 | +# Convert datetime to numeric values for plotting (e.g., using matplotlib date format) |
| 33 | +#am_time_numeric = pd.to_numeric(pd.to_datetime(am_time_datetime)) |
| 34 | + |
| 35 | +# Extract data and replace missing values |
| 36 | +#am_data = am.data |
| 37 | +#am_data = np.where(am_data == -32767, np.nan, am_data) |
| 38 | + |
| 39 | +# Create the line plot using the full dataset with numeric x-axis |
| 40 | + |
| 41 | + |
| 42 | +print(am[:10]) |
| 43 | +print(am_data[:10].data.datetime_as_string) |
| 44 | + |
| 45 | +cfp.gopen(file="Recipe3.png") # Start the plot |
| 46 | +cfp.lineplot( |
| 47 | + x=am_data, |
| 48 | + y=am, |
| 49 | + color="blue", |
| 50 | + title="Global Average Sea Surface Temperature", |
| 51 | + ylabel="Temperature (K)", |
| 52 | + xlabel="Time" |
| 53 | +) |
| 54 | + |
| 55 | +cfp.lineplot( |
| 56 | + x=am_data_copy, |
| 57 | + y=am_copy, |
| 58 | + color="red", |
| 59 | +) |
| 60 | +cfp.gclose() # Finish the plot |
| 61 | + |
| 62 | + |
| 63 | +# Save the plot to a file using matplotlib |
| 64 | +plt.savefig("global_avg_sst_plot.png") |
| 65 | + |
| 66 | +# Show the plot interactively |
| 67 | +plt.show() |
| 68 | + |
| 69 | +print("Plot created and saved successfully.") |
| 70 | + |
0 commit comments