我正在使用 pandas、xarray 和 matplotlib 從 .nc 檔案繪制一些時間序列。我有兩個資料集:
- 從 1982 年到 2019 年的海面溫度,我從中繪制了我所在地區的月平均值,并代表了這 37 年的月溫度變化。
- 海面溫度從 2020 年到 2021 年,我繪制了每年的月變化。
兩個繪制此圖,我使用以下代碼(請注意,由于記憶體分配問題,我在遍歷變數時遇到了記憶體分配問題,我撰寫了一個沒有回圈的非常基本的代碼,抱歉!)
import xarray as xr
import matplotlib.pyplot as plt
from matplotlib import dates as md
import pandas as pd
import numpy as np
import netCDF4
import seaborn as sns
import marineHeatWaves as mhw
import datetime
sns.set()
ds_original = xr.open_dataset('sst_med_f81_to21_L4.nc')
ds_original_last = xr.open_dataset('sst_med_f20_to21_L4.nc')
extract_date = datetime.datetime.today()
date = extract_date.strftime("%Y-%m-%d")
ds1 = ds_original.sel(time=slice('1982-01-01','2019-12-31'))
ds2 = ds_original_last.sel(time=slice('2020-01-01','2020-12-31'))
ds3 = ds_original_last.sel(time=slice('2021-01-01', date))
# Convert to Pandas Dataframe
df1 = ds1.to_dataframe().reset_index().set_index('time')
df2 = ds2.to_dataframe().reset_index().set_index('time')
df3 = ds3.to_dataframe().reset_index().set_index('time')
#Converting to Celsius
def kelvin_to_celsius(temp_k):
"""
Receives temperature in K and returns
temperature in Co
"""
temp_c = temp_k - 273.15
return temp_c
df1['analysed_sst_C'] = kelvin_to_celsius(df1['analysed_sst'])
df2['analysed_sst_C'] = kelvin_to_celsius(df2['analysed_sst'])
df3['analysed_sst_C'] = kelvin_to_celsius(df3['analysed_sst'])
#Indexing by month and yearday
df1['month'] = df1.index.month
df1['yearday'] = df1.index.dayofyear
df2['month'] = df2.index.month
df2['yearday'] = df2.index.dayofyear
df3['month'] = df3.index.month
df3['yearday'] = df3.index.dayofyear
# Calculating the average
daily_sst_82_19 = df1.analysed_sst_C.groupby(df1.yearday).agg(np.mean)
daily_sst_2020 = df2.analysed_sst_C.groupby(df2.yearday).agg(np.mean)
daily_sst_2021 = df3.analysed_sst_C.groupby(df3.yearday).agg(np.mean)
# Quick Plot
sns.set_theme(style="whitegrid")
fig, ax=plt.subplots(1, 1, figsize=(15, 7))
ax.xaxis.set_major_locator(md.MonthLocator())
ax.xaxis.set_major_formatter(md.DateFormatter('%b'))
ax.margins(x=0)
plt.plot(daily_sst_82_19, label='1982-2019')
plt.plot(daily_sst_2020,label='2020')
plt.plot(daily_sst_2021,label='2021', c = 'black')
plt.legend(loc = 'upper left')
我得到以下情節:

我希望我的情節從 Jan 開始,Dec 結束,但我不知道問題出在哪里。我試圖在特定日期之間設定 x 軸限制,但這會產生沖突,因為其中一個時間序列是 37 年,另外兩個是 1 年。
任何幫助將不勝感激!
更新
我想出了如何移動月份,指定以下內容:
ax.xaxis.set_major_locator(MonthLocator(bymonthday=2))
所以我得到了這個:

但是我仍然需要洗掉去年一月的那個,我不知道該怎么做。
uj5u.com熱心網友回復:
好的,所以我想出了如何解決這個問題。
微調繪圖引數,我將 DateFormatter 切換到 %D,以查看年份。令我驚訝的是,這一年被設定為 1970 年,我不知道為什么,因為我最舊的資料集始于 1981 年。所以一旦我發現了這一點,我將 xlims 設定為您可以在下面閱讀的那些,它運行得非常好:
#Add to plot settings:
ax.set_xlim(np.datetime64('1970-01-01'), np.datetime64('1970-12-31'))
ax.xaxis.set_major_locator(MonthLocator(bymonthday=1))
ax.xaxis.set_major_formatter(md.DateFormatter('%b'))
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390061.html
