1

I have the following code and was wondering how I could format the time to read in a 12 hr format. e.g. 0:00, 3:30, 10:00 etc. as of now the y axis reads 00:00:00, 00:01:00, 00:02:00 and so on. The data in the csv was formatted like this, 0:00, 1:00,2:00 etc.

How could I go about formatting the y axis to the format I need to?

Here is the code I have:

import pandas as pd
import matplotlib.pyplot as plt
import datetime

data = pd.read_csv('data.csv', sep=',', header=None)

ints = data[data[1]=='INT']
exts = data[data[1]=='EXT']

int_times = [datetime.datetime.time(datetime.datetime.strptime(t, '%H:%M')) 
             for t in ints[4]]
ext_times = [datetime.datetime.time(datetime.datetime.strptime(t, '%H:%M')) 
             for t in exts[4]]
int_dist = [d for d in ints[3]]
ext_dist = [d for d in exts[3]]

axis_times = ['0:00','01:00', '02:00', '03:00', '04:00', '05:00','06:00',
              '07:00','08:00','09:00','10:00','11:00','12:00']

fig, ax = plt.subplots()
ax.scatter(int_dist, int_times, c='red', s=50)
ax.scatter(ext_dist, ext_times, c='blue', s=50)

plt.yticks( axis_times, size='small')

plt.legend(['INT', 'EXT'], loc=4)
plt.xlabel('Distance')
plt.ylabel('Time')

plt.show()

Here is an image of what the graph shows: enter image description here

1 Answer 1

3

Use DateFormatter:

import matplotlib.dates as md
yfmt = md.DateFormatter('%H:%M')
ax.yaxis.set_major_formatter(yfmt)
Sign up to request clarification or add additional context in comments.

5 Comments

where did you get ymft and md from?
thanks to @ubuntu for including matplotlib as md; ymft is a variable that I declare
@hankharrison I believe yfmt is short for y axis format and md is short for m = matplotlib and d = dates
where do i place that code at that it doesn't seem to be working?
can you update the code to show where you included it?

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.