5

绘制箭袋或倒钩的时间序列(日期)的标准方法是什么?我经常在 Pandas DataFrame 中有时间序列,并像这样绘制它们:

plt.plot(df.index.to_pydatetime(), df.parameter)

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

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

TypeError: float() argument must be a string or a number

这可以通过以下方式克服:

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())

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

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

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())

在此处输入图像描述

4

2 回答 2

3

我最终使用了以下代码:

idx = mpl.dates.date2num(df.index)
ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('%d-%m-%Y'))

ax.plot(idx, df.V * 0.1 + 4, 'o-',color='k')
ax.quiver(idx, np.ones(size) * 3.5, df.U.values, df.V.values, pivot='mid')
ax.barbs(idx, np.ones(size) * 6.5, df.U.values, df.V.values, length=8, pivot='middle')
于 2012-12-20T10:17:25.333 回答
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()
于 2012-12-19T18:20:51.050 回答