python - Pandas and Matplotlib - fill_between() vs datetime64 -


there pandas dataframe:

<class 'pandas.core.frame.dataframe'> int64index: 300 entries, 5220 5519 data columns (total 3 columns): date             300 non-null datetime64[ns]                300 non-null float64 b                300 non-null float64 dtypes: datetime64[ns](1), float64(2) memory usage: 30.5 kb 

i want plot , b series vs date.

plt.plot_date(data['date'], data['a'], '-') plt.plot_date(data['date'], data['b'], '-') 

then want apply fill_between() on area between , b series:

plt.fill_between(data['date'], data['a'], data['b'],                 where=data['a'] >= data['b'],                 facecolor='green', alpha=0.2, interpolate=true) 

which outputs:

typeerror: ufunc 'isfinite' not supported input types, , inputs not safely coerced supported types according casting  rule ''safe'' 

does matplotlib accept pandas datetime64 object in fill_between() function? should convert different date type?

pandas registers converter in matplotlib.units.registry converts number of datetime types (such pandas datetimeindex, , numpy arrays of dtype datetime64) matplotlib datenums, not handle pandas series dtype datetime64.

in [67]: import pandas.tseries.converter 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 checks , uses converter handle data if exists.

so workaround, convert dates 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 np import matplotlib.pyplot plt import pandas 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() 

enter image description here


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -