1

I have two lists containing the sunset and sunrise times and the corresponding dates. It looks like:

sunrises = ['06:30', '06:28', '06:27', ...]
dates = ['3.21', '3.22', '3.23', ...]

I want to make a plot of the sunrise times as the Y axis and the dates as the X axis. Simply using

ax.plot(dates, sunrises)
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(7))
ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(7))
plt.show()

can plot the dates correctly, but the time is wrong: actual plot

And actually, the sunrise time isn't supposed to be a straight line.

How do I solve this problem?

Jason Jia
  • 42
  • 6

2 Answers2

3

You need to transform the datetime in string format to the format that matplotlib can comprehend by using datetime

from matplotlib import pyplot as plt 
import matplotlib as mpl
from datetime import datetime
import matplotlib.dates as mdates

sunrises = ['06:30', '06:28', '06:27',]
sunrises_dt = [datetime.strptime(item,'%H:%M') for item in sunrises]
dates = ['3.21', '3.22', '3.23',]

fig,ax = plt.subplots()
ax.plot(dates, sunrises_dt)
ax.yaxis.set_major_formatter(mdates.DateFormatter('%H:%M',))
ax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(1))

plt.show() 

enter image description here

meTchaikovsky
  • 7,478
  • 2
  • 15
  • 34
  • 1
    I'd recommend doing the same to `dates` as well: convert with `datetime.strptime(item,'%m.%d')` and format `ax.xaxis` with `mdates.DateFormatter('%m.%d')` – tdy Mar 27 '22 at 03:11
  • Wow, thanks! Now the data finally plots correctly. – Jason Jia Apr 03 '22 at 02:15
2

This is because your sunrises are not numerical. I'm assuming you'd want them in a form such that "6:30" means 6.5. Which is calculated below:

import matplotlib.pyplot as plt

sunrises = ['06:30', '06:28', '06:27']
# This converts to decimals
sunrises = [float(x[0:2])+(float(x[-2:])/60) for x in sunrises]
dates = ['3.21', '3.22', '3.23']

plt.plot(sunrises, dates)
plt.xlabel('sunrises')
plt.ylabel('dates')
plt.show()

Plot


Note, your dates are being treated as decimals. Is this correct?

Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29