【发布时间】:2022-01-21 23:35:57
【问题描述】:
我正在使用 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 Cº
"""
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')
我希望我的情节从一月开始,到十二月结束,但我不知道问题出在哪里。我试图在特定日期之间设置 x 轴限制,但这会产生冲突,因为其中一个时间序列为 37 年,而另外两个仅为 1 年。
任何帮助将不胜感激!
更新
我想出了如何移动月份,指定以下内容:
ax.xaxis.set_major_locator(MonthLocator(bymonthday=2))
所以我得到了这个:
但我仍然需要删除去年一月的那个,我不知道该怎么做。
【问题讨论】:
标签: python pandas matplotlib time-series python-xarray