4

I've got an error with the code below. This plot works well in Python2, but in Python3 i've got TypeError. Have no idea, how to fix it.

import matplotlib.pyplot as plt
from pylab import rcParams
import matplotlib.ticker as mtick
import matplotlib.dates as mdates
import numpy as np
import pandas as pd
from datetime import datetime, timedelta

DF = pd.DataFrame({
    'day':     [datetime(2018,1,1).date()+timedelta(x+1) for x in range(100)],
    'balance': np.random.normal(100,100,100)
})
rcParams['figure.figsize'] = 20, 10
fig, ax = plt.subplots()
ax.bar(DF['day'], DF['balance'], color='lightblue')
plt.xlabel('day', fontsize=20)
myFmt = mdates.DateFormatter('%Y-%m')
ax.xaxis.set_major_formatter(myFmt)
plt.show()

Error:

TypeError Traceback (most recent call last) in () 5 rcParams['figure.figsize'] = 20, 10 6 fig, ax = plt.subplots() ----> 7 ax.bar(DF['day'], DF['balance'], color='lightblue') 8 plt.xlabel('day', fontsize=20) 9 myFmt = mdates.DateFormatter('%Y-%m')

/home/anaconda3/lib/python3.6/site-packages/matplotlib/init.py in inner(ax, *args, **kwargs) 1896
warnings.warn(msg % (label_namer, func.name), 1897
RuntimeWarning, stacklevel=2) -> 1898 return func(ax, *args, **kwargs) 1899 pre_doc = inner.doc 1900 if pre_doc is None:

/home/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py in bar(self, left, height, width, bottom, **kwargs) 2103 if align == 'center': 2104 if orientation == 'vertical': -> 2105 left = [left[i] - width[i] / 2. for i in xrange(len(left))] 2106 elif orientation == 'horizontal': 2107 bottom = [bottom[i] - height[i] / 2.

/home/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py in (.0) 2103 if align == 'center': 2104
if orientation == 'vertical': -> 2105 left = [left[i] - width[i] / 2. for i in xrange(len(left))] 2106 elif orientation == 'horizontal': 2107 bottom = [bottom[i] - height[i] / 2.

TypeError: unsupported operand type(s) for -: 'datetime.date' and 'float'

1 Answer 1

4

Use date2num on the date column

Ex:

import matplotlib.pyplot as plt
from pylab import rcParams
import matplotlib.ticker as mtick
import matplotlib.dates as mdates
from matplotlib.dates import date2num       #-->Update
import numpy as np
import pandas as pd
from datetime import datetime, timedelta

DF = pd.DataFrame({
    'day':     [datetime(2018,1,1).date()+timedelta(x+1) for x in range(100)],
    'balance': np.random.normal(100,100,100)
})
rcParams['figure.figsize'] = 20, 10
fig, ax = plt.subplots()
DF['day'] = DF['day'].apply(date2num)      #-->Update

ax.bar(DF['day'], DF['balance'], color='lightblue')
plt.xlabel('day', fontsize=20)
myFmt = mdates.DateFormatter('%Y-%m')
ax.xaxis.set_major_formatter(myFmt)
plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

If you are not using time delta, you might see an error like this, AttributeError: 'DatetimeIndex' object has no attribute 'apply'solution is to use index.to_series().apply(date2num)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.