plt.set_title()中的标题字符串有误

2024-04-29 07:07:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xarray.Dataset,ds,带有一个时间变量,它是:

array([cftime.DatetimeGregorian(2021, 10, 16, 9, 50, 1, 0)], dtype=object)

我想使用地块标题中的日期,如下所示:

fig = plt.figure()
ax = plt.axes(projection = ccrs.PlateCarree(central_longitude=200))  # Orthographic
day_str = np.datetime_as_string(ds.time, unit='D').tobytes().decode()
ax.set_title(day_str, size = 10.)

我遇到的问题是,当我在标题中使用变量day_str时,它都是乱码

type(day_str)返回str。当我键入print(day_str)时,我得到:2021-10-16, 正如所料。因此,我不认为这是一个cftime到python日期时间的问题。我错过了什么

另一件相关的事情是,评估'foo' + day_str,给出:

'foo2\x00\x00\x000\x00\x00\x002\x00\x00\x001\x00\x00\x00-\x00\x00\x001\x00\x00\x000\x00\x00\x00-\x00\x00\x001\x00\x00\x006\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

编辑: 嗯,这不是很优雅,但很有效:

fig = plt.figure()
ax = plt.axes(projection = ccrs.PlateCarree(central_longitude=200))  # Orthographic
daystr=ds.time.dt.day.astype(str).values[0]
monstr=ds.time.dt.month.astype(str).values[0]
yrstr=ds.time.dt.year.astype(str).values[0]
day_str = monstr+'-'+daystr+'-'+yrstr
ax.set_title('SST, ' + day_str, size = 10.)

Tags: 标题time时间dtdsfigpltax
2条回答

xarray文档中关于时间序列的部分是一个很好的资源: http://xarray.pydata.org/en/stable/user-guide/time-series.html

处理此问题的一个好方法是将特殊的.dt访问器与方法.strftime一起使用:

day_str = ds.time.isel(time=-1).dt.strftime("%a, %b %d %H:%M").values

或者,在这种情况下

day_str=ds.time.dt.strftime("%a, %b %d %H:%M").values[0]

通过这种方法,'SST, ' + day_str给出

'SST, Tue, Oct 19 09:50'

就我对你的问题的理解而言,当我将你的DatetimeGregorian对象转换为字符串时,我得到的是:

import cftime
str(cftime.DatetimeGregorian(2021, 10, 16, 9, 50, 1, 0))

结果字符串:

'2021-10-16 09:50:01'

相关问题 更多 >