0

I'm trying to change the x axis of my graphs to appropriate datetime. I tried the answer from: Changing the formatting of a datetime axis in matplotlib but there seems to be an issue with my code.

This is the original graph. enter image description here Using this code:

csv = 'Hydro.csv'

df = pd.read_csv(csv, header=None, names=['time', 'mwp', 'ppld', 'mwd', 'shts', 'tides', 'tan B', 'Lo', 'E', 'wind speed', 'wind gust', 'wind direction'])
fig = plt.figure(tight_layout=False)
gs = gridspec.GridSpec(5, 1)

ax1 = fig.add_subplot(gs[0, :])
ax1.plot(df['time'], df['ppld'], label = 'Peak Wave Period', linewidth = 1, color ='k')
ax1.set_ylabel ('Tp[s]', size = 10)

ax1.grid(True, ls='--')
plt.setp(ax1.get_xticklabels(), visible=True, rotation = 90)

When I start adjusting the ticks, it doesn't plot my graph properly: enter image description here

csv = 'Hydro.csv'

df = pd.read_csv(csv, header=None, names=['time', 'mwp', 'ppld', 'mwd', 'shts', 'tides', 'tan B', 'Lo', 'E', 'wind speed', 'wind gust', 'wind direction'])
fig = plt.figure(tight_layout=False)
gs = gridspec.GridSpec(5, 1)

ax1 = fig.add_subplot(gs[0, :])
ax1.plot(df['time'], df['ppld'], label = 'Peak Wave Period', linewidth = 1, color ='k')
ax1.set_ylabel ('Tp[s]', size = 10)
ax1.grid(True, ls='--')

ax1.xaxis_date()
ax1.set_xticks(df['time'])
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%M:%D"))
ax1.xaxis.set_minor_formatter(mdates.DateFormatter("%H"))
_=plt.xticks(rotation=45)  


plt.show()

I want it to show 6 hour intervals and the day/month.

SiegmundNuyts
  • 67
  • 1
  • 12
  • There is no content (no line) being shown inside the axes. It's hard to find out why that would be the case without [mcve]. Once that is solved, one can tackle the ticking. – ImportanceOfBeingErnest Oct 04 '19 at 11:44
  • I assumed that was one of the issues... If I plot it with the date/time ticks, it is working (graph added). When I try to adjust the ticks, it's not showing anymore. – SiegmundNuyts Oct 04 '19 at 12:05
  • I see. You're plotting strings, right? That means there is no connection between a string (could be `"My wedding date"` as well) and a date. So first convert your string to dates. – ImportanceOfBeingErnest Oct 04 '19 at 12:12

1 Answers1

0

As suggested in the comments, I had to convert to dates first.

csv = 'Hydro.csv'

df = pd.read_csv(csv, header=None, names=['time', 'mwp', 'ppld', 'mwd', 'shts', 'tides', 'tan B', 'Lo', 'E', 'wind speed', 'wind gust', 'wind direction'])
xp = [datetime.strptime(d, "%d/%m/%Y %H:%M:%S") for d in df['time']]

xs = mdates.date2num(xp)
date = mdates.DateFormatter ("%d/%m/%Y\n%H:%M:%S")

fig = plt.figure(tight_layout=False)
gs = gridspec.GridSpec(5, 1)

ax1 = fig.add_subplot(gs[0, :])
ax1.xaxis.set_major_formatter(date)
ax1.xaxis.set_ticks_position('top')
ax1.set_ylabel ('$T_p[s]$', size = 10)
ax1.grid(True, ls='--')
ax1.plot(xs, df['ppld'], linewidth = 1, color = 'k')

SiegmundNuyts
  • 67
  • 1
  • 12