Thanks to visit codestin.com
Credit goes to github.com

Skip to content

problems with timestamps in matplotlib seems related to bug #9779 #11649

Closed
@danieljmr

Description

@danieljmr

Bug report

Bug summary

I am gettin the following error when trying to plot dates in X-axis. It seems that the same bug was reported in #9779 bug as I already have the fix I am wondering why I am still getting the error. Maybe something I am doing wrong?

The error is:
TypeError: ufunc subtract cannot use operands with types dtype('<M8[ns]') and dtype('float64')

input data is a csv with format:

TIMESTAMP,Call Waiting,Stand Waiting,Sat Waiting,Blocked,Send email,Break,Printing Document,in Meeting,Sending Mail,Driving car,Driving bike,Driving truck,Typing,Traffic Light Wait,Enter garage,Sleeping,on Call,Browsing
2018-05-04 17:00:13.254403,,,,,,,,,,,,,,,,,,
2018-05-04 17:00:20.486367,,,8,,,,7,,,1,,,47,4,1,,,
2018-05-04 17:00:28.915123,,,8,,,,,,,,,,,,,,,
2018-05-04 17:00:30.476002,,,8,,,,,,,,,,,,,,,
2018-05-04 17:00:30.504923,,,8,,,,2,,1,,,,69,1,1,,,
2018-05-04 17:00:33.612147,,,8,,,,11,,,,1,,47,2,,,,
2018-05-04 17:00:46.782256,,,8,,,,3,,,1,,,64,1,1,,,
2018-05-04 17:00:51.550413,,,7,,,,4,,,4,,,119,3,1,,,
2018-05-04 17:00:51.746899,,,8,,,,,,,,,,,,,,,
2018-05-04 17:00:56.773144,,,8,,,,,,,,,,1,,,,,
2018-05-04 17:01:01.164004,,,8,,,,,,,,,,,,,,,
2018-05-04 17:01:14.989166,1,,8,1,,,15,,,,,,91,2,,,,
2018-05-04 17:01:26.347999,1,,8,,,,14,,,1,,,61,2,1,,,

If TIMESTAMP is not converted to np.datenum64 the X-axis will be converted to numbers but it will dispay the graph ok

Code for reproduction

data['TIMESTAMP'] = pd.to_datetime(data['TIMESTAMP'])
bar = axes.bar(data['TIMESTAMP'], data[a], bottom=margin_bottom, label=a, color=palet[a], width=0.03)
margin_bottom += data[a]

import collections
from collections import OrderedDict
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import mpld3
from mpld3 import plugins
import datetime as dt
from datetime import datetime


input_file = 'activity.csv'

palet = OrderedDict({
'Call Waiting' : 'limegreen',
'Stand Waiting' : 'gold',
'Sat Waiting' : 'goldenrod',
'Blocked' : 'darkorchid',
'Send email' : 'coral',
'Break' : 'lightcoral',
'Printing Document' : 'orangered',
'in Meeting' : 'olivedrab',
'Sending Mail' : 'plum',
'Driving car' : 'orange',
'Driving bike' : 'c',
'Driving truck' : 'skyblue',
'Typing' : 'mediumslateblue',
'Traffic Light Wait' : 'darkturquoise',
'Enter garage' : 'orchid',
'Sleeping' : 'firebrick',
'on Call' : 'indianred',
'Browsing' : 'silver'
})

# Define CSS to control tooltips
css = """
.tooltip {
    position: relative;
    display: inline-block;
}
.tooltip .tooltiptext {
    background-color: #4c4c4c;
    color: #fff;
    text-align: center;
    padding: 5px 0;
    border-radius: 6px;
}
.tooltip .tooltiptext::after {
    content: " ";
    position: absolute;
    top: 50%;
    right: 100%; /* To the left of the tooltip */
    margin-top: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: transparent #4c4c4c transparent transparent;
}
"""

data = pd.read_csv(input_file,sep=',')
data = data.fillna( value = 0, axis = 0 )
data = data.sort_values('TIMESTAMP')
data['TIMESTAMP'] = pd.to_datetime(data['TIMESTAMP'])

fig = plt.figure(figsize=(20,8))
axes = fig.add_subplot(111)

margin_bottom = np.zeros(len(data.TIMESTAMP.drop_duplicates()))

for a in palet.keys():
        bar = axes.bar(data['TIMESTAMP'], data[a], bottom=margin_bottom, label=a, color=palet[a], width=0.03)
        margin_bottom += data[a]
        for rectangle in bar.get_children():
                if rectangle.get_height() > 0.0:
                        tooltip = mpld3.plugins.LineHTMLTooltip(rectangle, label="<div class=\"tooltip\"><span class=\"tooltiptext\">"+ a + ' : ' + str(rectangle.get_height()) + "</span></div>", voffset=-10, hoffset=10, css=css )
                        mpld3.plugins.connect(plt.gcf(), tooltip)

plugins.connect(fig, plugins.MousePosition(fontsize=14))

axes.legend()

mpld3.show()

Actual outcome

TypeError: ufunc subtract cannot use operands with types dtype('<M8[ns]') and dtype('float64')

Traceback (most recent call last):
  File "C:\MyDIR\MyStest.py", line 94, in <module>
    bar = axes.bar(data['TIMESTAMP'], data[a], bottom=margin_bottom, label=a, color=palet[a], width=0.03)
  File "C:\Users\ThatIsMe\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\__init__.py", line 1855, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\ThatIsMe\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 2259, in bar
    left = x - width / 2
TypeError: ufunc subtract cannot use operands with types dtype('<M8[ns]') and dtype('float64')

Expected outcome

X-axis showing dates. Dates can be plotted when using pandas directly but I need to perform customization like fixed colors for data types plotted as bars and sequence of bar stack

Matplotlib version

INSTALLED VERSIONS

commit: None
python: 3.6.5.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: English_United States.1252

pandas: 0.22.0
pytest: None
pip: 10.0.1
setuptools: 39.0.1
Cython: None
numpy: 1.14.3
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.7.2
pytz: 2018.4
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.2.2
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions