本文介绍了 pandas 和Matplotlib-fill_between()vs datetime64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个熊猫数据框:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 300 entries, 5220 to 5519
Data columns (total 3 columns):
Date             300 non-null datetime64[ns]
A                300 non-null float64
B                300 non-null float64
dtypes: datetime64[ns](1), float64(2)
memory usage: 30.5 KB

我想绘制A和B系列与日期的关系图.

I want to plot A and B series vs Date.

plt.plot_date(data['Date'], data['A'], '-')
plt.plot_date(data['Date'], data['B'], '-')

然后我要在A系列和B系列之间的区域上应用fill_between():

Then I want apply fill_between() on area between A and B series:

plt.fill_between(data['Date'], data['A'], data['B'],
                where=data['A'] >= data['B'],
                facecolor='green', alpha=0.2, interpolate=True)

哪个输出:

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs
could not be safely coerced to any supported types according to the casting 
rule ''safe''

matplotlib是否在fill_between()函数中接受熊猫datetime64对象?我应该将其转换为其他日期类型吗?

Does matplotlib accept pandas datetime64 object in fill_between() function? Should I convert it to different date type?

推荐答案

Pandas在matplotlib.units.registry中注册了一个转换器,该转换器将许多日期时间类型(例如pandas DatetimeIndex和dtype datetime64的numpy数组)转换为matplotlib datenums,但它不处理Pandas dtype datetime64.

Pandas registers a converter in matplotlib.units.registry which converts a number of datetime types (such as pandas DatetimeIndex, and numpy arrays of dtype datetime64) to matplotlib datenums, but it does not handle Pandas Series with dtype datetime64.

In [67]: import pandas.tseries.converter as converter

In [68]: c = converter.DatetimeConverter()

In [69]: type(c.convert(df['Date'].values, None, None))
Out[69]: numpy.ndarray              # converted (good)

In [70]: type(c.convert(df['Date'], None, None))
Out[70]: pandas.core.series.Series  # left unchanged

fill_between检查并使用转换器来处理数据(如果存在).

fill_between checks for and uses a converter to handle the data if it exists.

作为一种解决方法,您可以将日期转换为datetime64的NumPy数组:

So as a workaround, you could convert the dates to a NumPy array of datetime64's:

d = data['Date'].values
plt.fill_between(d, data['A'], data['B'],
                where=data['A'] >= data['B'],
                facecolor='green', alpha=0.2, interpolate=True)


例如,


For example,

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

N = 300
dates = pd.date_range('2000-1-1', periods=N, freq='D')
x = np.linspace(0, 2*np.pi, N)
data = pd.DataFrame({'A': np.sin(x), 'B': np.cos(x),
               'Date': dates})
plt.plot_date(data['Date'], data['A'], '-')
plt.plot_date(data['Date'], data['B'], '-')

d = data['Date'].values
plt.fill_between(d, data['A'], data['B'],
                where=data['A'] >= data['B'],
                facecolor='green', alpha=0.2, interpolate=True)
plt.xticks(rotation=25)
plt.show()

这篇关于 pandas 和Matplotlib-fill_between()vs datetime64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:34