0

I am reading the text file that has two columns in the next format:

20120101 5.6
20120102 5.3
20120103 5.4
...

Where the first column is YYYYMMDD yearmonthday and the second is a magnitude.

Here's what I am doing so far:

file = open('junk.txt','r')
lines = file.readlines()
file.close()

Magnitude=[]
Year=[]

for line in lines:
    p=line.split()

    Year.append(str(p[0]))
    Magnitude.append(float(p[5]))

year = np.array(Year, dtype='datetime64[Y]')
mag=np.array(Magnitude)

fig2 = plt.figure()
ax2 = fig2.add_subplot(1,1,1)
ax2.plot_date(year, Cmag, color='k',linestyle='-',linewidth=2.0)
ax2.set_xlabel('Number of Events')
ax2.set_ylabel('Cumulative Moment')

However the format of the x axis (time) is not correct. I would like to display the time in the format: yyymm in the x axis.

Here's a link with my output (figure):

https://drive.google.com/a/ucsc.edu/file/d/0B3Y1nDlkfy2VNjlBS2FrT0ZRWW8/view?usp=sharing

You can see that time isn't recognized correctly.

user3666197
  • 1
  • 6
  • 50
  • 92

1 Answers1

0

matplotlib has a special datetime value ( processing & formatting )

So, a two-step story to get 'em PLOT really nice

enter image description here

Step 1: prepare data into a proper format

from a datetime to a matplotlib convention compatible float for dates/times


As usual, devil is hidden in detail.

matplotlib dates are almost equal, but not equal:

#  mPlotDATEs.date2num.__doc__
#                  
#     *d* is either a class `datetime` instance or a sequence of datetimes.
#
#     Return value is a floating point number (or sequence of floats)
#     which gives the number of days (fraction part represents hours,
#     minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
#     The addition of one here is a historical artifact.  Also, note
#     that the Gregorian calendar is assumed; this is not universal
#     practice.  For details, see the module docstring.

So, highly recommended to re-use their "own" tool:

from matplotlib import dates as mPlotDATEs   # helper functions num2date()
#                                            #              and date2num()
#                                            #              to convert to/from.

Step 2: manage axis-labels & formatting & scale (min/max) as a next issue

matplotlib brings you arms for this part too.

from matplotlib.dates   import  DateFormatter,    \
                                AutoDateLocator,   \
                                HourLocator,        \
                                MinuteLocator,       \
                                epoch2num
from matplotlib.ticker  import  ScalarFormatter, FuncFormatter

aPlotAX.xaxis.set_major_formatter( DateFormatter( '%Y%m' ) )  # OUGHT WORK

Check code in this answer for all details

Community
  • 1
  • 1
user3666197
  • 1
  • 6
  • 50
  • 92