0

I have a 1D array of date ordinals extracted from the datetime module. This array holds the ordinals as floats.

I plotted a figure by using matplotlib pyplot as such:

import numpy as np
from datetime import datetime as dt
from matplotlib import pyplot as plt

f = plt.plot(newdates, surge)

The newdates and surge 1D arrays are of the same size. What I want to know if how to setup the dateticks as dates instead of the date ordinals. For example newdates[0] = array([710397.]) So in my figure, the first tick will be 710397, but I want the date as %m%Y format instead. Is there a way to do this directly? I attach my figure for reference.

see my figure here

Madlad
  • 125
  • 12

1 Answers1

0

assuming this relates to your other question, I suggest you don't use the ordinal at all. You can simply use datetime objects and format the plot appropriately:

from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# some dummy data...
data_to_plot = np.array([1,3,2,4]) 

# taken from the linked question:
yr = np.array([1946, 1946, 1946, 1946], dtype=np.int)
mon = np.array([1, 1, 1, 1], dtype=np.int)
day = np.array([1, 1, 1, 1], dtype=np.int)
hr = np.array([1, 2, 3, 4], dtype=np.int)
# cast year/month/day/hour to datetime object:
newdates = [datetime(y,m,d,h) for y, m, d, h in zip(yr, mon, day, hr)]

# examplary plot
fig, ax = plt.subplots(1)
plt.plot(newdates, data_to_plot)
# format the tick labels:
xfmt = mdates.DateFormatter('%Y-%m-%d %H h')
ax.xaxis.set_major_formatter(xfmt)
# make one label every hour:
hours = mdates.HourLocator(interval = 1)
ax.xaxis.set_major_locator(hours)
# rotate the labels:
plt.xticks(rotation=45)
# adjust the canvas so that the labels are visible:
plt.subplots_adjust(top=0.90, bottom=0.22, left=0.10, right=0.9)
plt.show()

enter image description here

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Thank you so much MrFuppes. I definetely see now what you were referring to in my other question. I am still a noob to python and just learning as I am analyzing my data, so I really appreciate your help with my question!!! I also come from Matlab stuff so I can get pretty stubborn on a certain way of doing things. Thank you again :) – Madlad Jun 21 '20 at 23:38
  • @JirehGarcia: glad I could help! From my experience, nice plots are a bit easier to have in MATLAB than in Python, so no worries ;-) You'll get used to the Python way of doing this. – FObersteiner Jun 22 '20 at 06:55