2

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?

1
  • Are you trying to plot these as a line chart? Commented Mar 27, 2022 at 2:50

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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')
Wow, thanks! Now the data finally plots correctly.
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?

2 Comments

Thanks freddy, this is a great idea. Maybe I can transform the times to floats. But in this program I want to still display the time labels as the format %H:%M.
No problem Jason, The other answer keeps the labels in %H:%M format

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.