简体   繁体   中英

How to set minutes time as x-axis of a Matplotlib plot in Python?

I'm trying to set minutes time as x-axis of matplotlib plot.The time period is from 8:30 to 15:00 everyday.I only need minutes time,don't need date.

currently I only know how to set date as x-axis:

from datetime import datetime

import matplotlib.dates as mdates
import matplotlib.pyplot as plt

dates = ['01/02/1991', '01/03/1991', '01/04/1991']
xs = [datetime.strptime(d, '%m/%d/%Y').date() for d in dates]
ys = range(len(xs))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
# Plot
plt.plot(xs, ys)
plt.gcf().autofmt_xdate()  
plt.show()

Any friend can help?

Here's one way you can generate the desired plot:

from datetime import date, datetime, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as md

#a generator that gives time between start and end times with delta intervals
def deltatime(start, end, delta):
    current = start
    while current < end:
        yield current
        current += delta
dates = ['01/02/1991', '01/03/1991', '01/04/1991']

# generate the list for each date between 8:30 to 15:00 at 30 minute intervals
datetimes=[]
for i in dates:
    startime=datetime.combine(datetime.strptime(i, "%m/%d/%Y"), datetime.strptime('8:30:00',"%H:%M:%S").time())
    endtime=datetime.combine(datetime.strptime(i, "%m/%d/%Y"), datetime.strptime('15:00:00',"%H:%M:%S").time())
    datetimes.append([j for j in deltatime(startime,endtime, timedelta(minutes=30))])

#flatten datetimes list
datetimes=[datetime for day in datetimes for datetime in day]
xs = datetimes
ys = range(len(xs))

# plot
fig, ax = plt.subplots(1, 1)
ax.plot(xs, ys,'ok')

# From the SO:https://stackoverflow.com/questions/42398264/matplotlib-xticks-every-15-minutes-starting-on-the-hour
## Set time format and the interval of ticks (every 240 minutes)
xformatter = md.DateFormatter('%H:%M')
xlocator = md.MinuteLocator(interval = 240)

## Set xtick labels to appear every 240 minutes
ax.xaxis.set_major_locator(xlocator)

## Format xtick labels as HH:MM
plt.gcf().axes[0].xaxis.set_major_formatter(xformatter)
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM