带日期轴的箭袋或倒钩 [英] Quiver or Barb with a date axis
问题描述
绘制颤动或倒钩的时间序列(日期)的标准方法是什么?我通常在Pandas DataFrame中有时间序列,并按如下方式绘制它们:
What is the standard way of plotting a timeseries (dates) of quiver or barbs? I often have timeseries in a Pandas DataFrame and plot them like this:
plt.plot(df.index.to_pydatetime(), df.parameter)
这很好用,可以将x轴视为真实日期,这对于使用Datetime对象等格式化或设置xlim()非常方便.
This works very well, the x-axis can be treated as genuine dates which is very convenient for formatting or setting the xlim() with Datetime object etc.
以相同的方式将其与箭袋或倒钩一起使用会导致:
Using this with quiver or barbs in the same way result in:
TypeError: float() argument must be a string or a number
这可以通过以下方式克服:
This can be overcome with something like:
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())
这是可行的,但是这意味着我到处都必须将日期转换为浮点数,然后手动覆盖标签.有更好的方法吗?
Which works, but would mean that everywhere i have to convert the dates to floats and then manually override the labels. Is there a better way?
以下是一些与我的情况类似的示例代码:
Here is some sample code resembling my case:
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())
推荐答案
我建议将日期转换为时间戳,然后使用自定义格式化程序( doc ),使其看起来更好(就间距/标签的贴合度而言.)
I would suggest converting your dates to timestamps, and then using a custom formatter (doc) to convert the seconds to date format of your choice. You will probably have to play with the locator (doc) a bit to get it to look good (in terms of spacing/labels fitting).
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()
这篇关于带日期轴的箭袋或倒钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!