Reputation: 21
I have a dataset containing ocean temperature values for the time period 1950-2022, covering the entire globe. My goal is to calculate the linear trend for each surface grid box and visualize the results as a two-dimensional map (longitude versus latitude).How can I make loop through each grid box in the dataset and use numpy.polyfit to obtain the linear trend coefficient for each box?I used this code After extracting the necessary variables (time, longitude, latitude, and ocean temperature) from the dataset, I plan to follow these steps:
for i in range(lon): for j in range(lat): Temp_box = temp[:, j, i]
trend_coefficients = np.polyfit(time, Temp_box, deg=1)
trend[j, i] = trend_coefficients[0]
plt.contourf(lon,lat,trend,cmap='PuBu')
Upvotes: 0
Views: 55
Reputation: 25023
If your data is arranged in a 3D array with axes x
, y
and t
you can address a geo-located time series as temperature_time_series = z[x, y]
.
The following code shows you how you can use Numpy to fit a linear trend to each time series using a list comprehension.
In [49]: %reset -f
...:
...: import matplotlib.pyplot as plt
...: import numpy as np
...: fit = np.polynomial.Polynomial.fit
...:
...: # generate data
...: W, H, D = 4, 5, 8
...: x = np.arange(W) ; y = np.arange(H)
...: z = np.array([[np.linspace(0, X+Y, D) for X in x] for Y in y])
...:
...: # compute trends
...: rD = np.arange(D) # or matbe rD = np.arange(Year_min, Year_max+1)
...: trends = np.array([[fit(rD, col, 1).coef[1] for col in row] for row in z])
...:
...: # print trends
...: for row, Y in zip(trends, y):
...: print(' '.join("(%d, %d, %.2f)"%(X, Y, T) for T, X in zip(row, x)))
...: #
...:
(0, 0, 0.00) (1, 0, 0.50) (2, 0, 1.00) (3, 0, 1.50)
(0, 1, 0.50) (1, 1, 1.00) (2, 1, 1.50) (3, 1, 2.00)
(0, 2, 1.00) (1, 2, 1.50) (2, 2, 2.00) (3, 2, 2.50)
(0, 3, 1.50) (1, 3, 2.00) (2, 3, 2.50) (3, 3, 3.00)
(0, 4, 2.00) (1, 4, 2.50) (2, 4, 3.00) (3, 4, 3.50)
In [50]:
Upvotes: 0