TAGS :Viewed: 8 - Published at: a few seconds ago

[ matplotlib: Convert Hour string to float ]

I'm trying to plot the following csv data as the x-axis with matplotlib:

Time
00:00:00
01:00:00
02:00:00
03:00:00
04:00:00
05:00:00
06:00:00
07:00:00
08:00:00
09:00:00
10:00:00
11:00:00
12:00:00
13:00:00
14:00:00
15:00:00
16:00:00
17:00:00
18:00:00
19:00:00
20:00:00
21:00:00
22:00:00
23:00:00

But I keep getting the error:

ValueError: could not convert string to float: '23:00:00'

How Can I convert these values to Hour format in matplotlib?

Here is my code:

fig = plt.figure(figsize=(15,7))
ax = fig.add_subplot(1,1,1) # row-col-num
# --- line plot data on the Axes
ax.plot(df3['YYYY-MO-DD HH-MI-SS_SSS'], df3['ATMOSPHERIC PRESSURE (hPa) mean'], 'b-', linewidth=2,
label=r'office Phone1')

Any ideas?

Thank you !

Answer 1


The error message

ValueError: could not convert string to float: '23:00:00'

implies that one of the inputs -- probably df3['YYYY-MO-DD HH-MI-SS_SSS'] -- contains strings when ax.plot was expecting floats.

ax.plot, however, can accept datetime-like objects instead of floats as well. So it would suffice to convert df3['YYYY-MO-DD HH-MI-SS_SSS'] to datetime-like objects.

Using pandas, you can do that using the parse_dates parameter of pd.read_csv (assuming df3 is defined with pd.read_csv), or you can convert that column to datetime-like objects after-the-fact:

date_col = 'YYYY-MO-DD HH-MI-SS_SSS'
df3[date_col] = pd.to_datetime(df3[date_col])

For example,

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

np.random.seed(2016)
date_col = 'YYYY-MO-DD HH-MI-SS_SSS'

df = pd.DataFrame( {date_col: [
    '00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00',
    '06:00:00', '07:00:00', '08:00:00', '09:00:00', '10:00:00', '11:00:00',
    '12:00:00', '13:00:00', '14:00:00', '15:00:00', '16:00:00', '17:00:00',
    '18:00:00', '19:00:00', '20:00:00', '21:00:00', '22:00:00', '23:00:00'],
                'foo': np.random.random(24)})
df[date_col] = pd.to_datetime(df[date_col])

fig, ax = plt.subplots()
ax.plot(df[date_col], df['foo'], 'b-', linewidth=2, label='foo')
plt.show()

enter image description here