简体   繁体   中英

Formatting X-Axis Time in Python

I'm plotting data from a text file with two columns that are delimited by a comma. The first column is time that is formatted in %H:%S . The second line are numbers.

Right now, the coding that I have is displaying %Y%m%d %H:%M:%s instead of %H:%M . As you can see, there are a lot of entries and they are overlapping each other. How can I make the ticks skip every 1 or 2 to make the times more visible?

How can I correct this?

File Contents:

09:30,33.89
09:34,34.17
09:39,34.41
09:44,34.20
09:49,34.40

Script:

#!/usr/bin/python
from __future__ import division
import sys
import csv
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np

homedir = '/home//'

ymd = sys.argv[1]
sym = sys.argv[2]

x,y = [],[]
csv_reader = csv.reader(open(homedir + 'finance/data/' + sym + '_' + ymd))
for line in csv_reader:
    x.append(dt.datetime.strptime(line[0], '%H:%M'))
    y.append(str(line[1]))

fig = plt.figure()
ax = fig.add_subplot(111)

#ax.grid(which='both')

ax.plot(x,y,'-',ms=3,linewidth=1)
#fig.autofmt_xdate(x,rotation=90,ha='center')
plt.xticks(x, x, rotation=90,ha='center')
plt.title('Daily Market Data for ' + sym + ' on ' + ymd)
plt.ylabel('Stock Price [$]')
plt.xlabel('Time of Day')
plt.grid(True)

fig.set_size_inches(9,5)

plt.savefig(homedir + 'finance/' + sym + '_' + ymd + '.png', dpi = 300, bbox_inches='tight')
#plt.show()

Plot:

在此处输入图片说明

datetime.strptime() parses a string time to a datetime object using the second argument to map the values from the original string to the datetime components. Here's a couple guides explaining the difference between strptime() and strftime() .

Anyways, I guess you could just use the original strings for your xticks and leave the line that builds the x list for your plot alone, since it seems to work adequately.

Try changing your for loop section to this:

x,y,xticks = [],[],[]
csv_reader = csv.reader(open(homedir + 'finance/data/' + sym + '_' + ymd))
for line in csv_reader:
    xticks.append(line[0])
    x.append(dt.datetime.strptime(line[0], '%H:%M'))
    y.append(str(line[1]))

Then, of course, get rid of your other xticks assignment and change your plt.xticks call to this:

plt.xticks(x, xticks, rotation=90,ha='center')

Edit: OP added to the question, I'll give some brief advice.

Maybe do something hacky in your for loop like

for line in csv_reader:
    time = dt.datetime.strptime(line[0], '%H:%M')
    if time.minute % 5 == 0:
        xticks.append(line[0])
    else:
        xticks.append("")
    x.append(time)
    y.append(str(line[1]))

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