0

I have a column that has time like 9:3:15 (no leading 0s) (3 mins and 15 sec past 9). I would like to plot this (no date, just time) on the x axis. so i tried the following code:

def data_vis(dayN):
    plt.subplots_adjust(bottom=0.2)
    plt.xticks( rotation=25 )
    ax=plt.gca()
    #ax.xaxis_date()
    xfmt = md.DateFormatter('%H:%MM:%S')
    ax.xaxis.set_major_formatter(xfmt)
    plt.plot_date(md.date2num(dayN["Time Stamp"]),dayN["Temperature(deg C)"])
    plt.show()

I got the following error:

DateFormatter found a value of x=0, which is an illegal date; this usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()

with ax.xaxis_date() enabled, I got the below error.

'str' object has no attribute 'toordinal'

Since that columns was "str", I thought of using

pd.to_datetime(day2["Time Stamp"], format = '%H:%M:%S)

but it results in the below output:

1900-01-01 09:51:33

Now I would like to try datetime.datetime.strptime using map and/or lambda function for the above said column..

Any help regarding implementation of map function and plotting the data would be really helpful.Also wil the datetime.strptime help in resolving the problem?

thanks,

1 Answers1

0

not sure what's going wrong here; the following works fine for me:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.dates as md
# create a dummy df...
dayN = pd.DataFrame({"Temperature(deg C)": np.random.rand(10)+20,
                     "Time Stamp": ['9:3:15','9:3:16','9:3:17','9:3:18','9:3:19',
                                    '9:3:20','9:3:21','9:3:22','9:3:23','9:3:24']})
# format to datetime, don't care about the date:
dayN["Time Stamp"] = pd.to_datetime(dayN["Time Stamp"], format='%H:%M:%S')

plt.subplots_adjust(bottom=0.2)
plt.xticks(rotation=25)
ax = plt.gca()
xfmt = md.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)
plt.plot_date(md.date2num(dayN["Time Stamp"]), dayN["Temperature(deg C)"])
plt.show()

enter image description here

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • I think that because of the no. of entries in my data, matplotlib only shows hourly time like 9:00:00 , 12:00:00 15:00:00. I read it from the comments to the ans here [link]here:https://stackoverflow.com/a/4091264/12129327 thanks for a solution really appreciate it! – Somasundharam Sampath May 08 '20 at 13:51
  • @SomasundharamSampath: maybe you need to set custom ticks then, see e.g. [here](https://stackoverflow.com/questions/48790378/how-to-get-ticks-every-hour) or [matplotlib docs](https://matplotlib.org/3.1.3/gallery/text_labels_and_annotations/date_index_formatter.html) – FObersteiner May 08 '20 at 13:59