Home > OS >  How to plot time on the y axis correctly using python matplotlib?
How to plot time on the y axis correctly using python matplotlib?

Time:03-27

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?

CodePudding user response:

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

CodePudding user response:

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?

  • Related