带日期轴的箭袋或倒钩

Rut*_*ies 5 python matplotlib pandas

绘制颤动或倒钩的时间序列(日期)的标准方法是什么?我通常在Pandas DataFrame中有时间序列,并按如下方式绘制它们:

plt.plot(df.index.to_pydatetime(), df.parameter)
Run Code Online (Sandbox Code Playgroud)

这很好用,x轴可以视为真实日期,这对于使用Datetime对象等格式化或设置xlim()非常方便。

以相同的方式将其与箭袋或倒钩一起使用会导致:

TypeError: float() argument must be a string or a number
Run Code Online (Sandbox Code Playgroud)

可以通过以下方法解决:

ax.barbs(df.index.values.astype('d'), np.ones(size) * 6.5, df.U.values, df.V.values, length=8, pivot='middle')
ax.set_xticklabels(df.index.to_pydatetime())
Run Code Online (Sandbox Code Playgroud)

哪个可行,但是这意味着我到处都必须将日期转换为浮点数,然后手动覆盖标签。有没有更好的办法?

这是一些类似于我的案例的示例代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

size = 10

wspd = np.random.randint(0,40,size=size)
wdir = np.linspace(0,360 * np.pi/180, num=size)
U = -wspd*np.sin(wdir)
V = -wspd*np.cos(wdir)

df = pd.DataFrame(np.vstack([U,V]).T, index=pd.date_range('2012-1-1', periods=size, freq='M'), columns=['U', 'V'])

fig, ax = plt.subplots(1,1, figsize=(15,4))

ax.plot(df.index.values.astype('d'), df.V * 0.1 + 4, color='k')
ax.quiver(df.index.values.astype('d'), np.ones(size) * 3.5, df.U.values, df.V.values, pivot='mid')
ax.barbs(df.index.values.astype('d'), np.ones(size) * 6.5, df.U.values, df.V.values, length=8, pivot='middle')

ax.set_xticklabels(df.index.to_pydatetime())
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

tac*_*ell 2

我建议将您的日期转换为时间戳,然后使用自定义格式化程序(doc)将秒数转换为您选择的日期格式。您可能需要稍微使用一下定位器(doc)才能使其看起来不错(在间距/标签拟合方面)。

import datetime
def tmp_f(dt,x=None):
    return datetime.datetime.fromtimestamp(dt).isoformat()
mf = matplotlib.ticker.FuncFormatter(tmp_f)

ax = gca()
ax.get_xaxis().set_major_formatter(mf)
draw()
Run Code Online (Sandbox Code Playgroud)