Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I format tickers for hh:mm in Python matplotlib over a fixed period

I am fairl amateur to programming, but I’m trying to create a python widget that can display the selected photoperiod for a controlled environment growhouse, based on the current time. A GUI would contain this widget so I can know the programmed light hours remotely.

I’m in the early stages of making this and have hit a wall trying to set the time format for the axis.

As you can see in the image, I want to plot the current time against a set time line, with set tickers/intervals.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any suggestions on improvement are welcome, it’s very early days for my Python journey so simple and constructive help or guides appreciated please 🙂

This is the concept:

(https://i.sstatic.net/x0Z4vsiI.png)

This is my current code:

import matplotlib.pyplot as plt
import matplotlib.dates as md
import datetime
import numpy as np
import matplotlib.ticker as plticker




#Creating an object for the current date and time
timenowfull = datetime.datetime.now()


#converting current time to hh:mm
timenowMMHH = (timenowfull.strftime("%H:%M"))

#testing the current time converted readout
print(timenowMMHH)


dataY = np.array([0.5])
dataX = np.array([timenowMMHH])


plt.ylim(0, 1) 
plt.locator_params(axis='y', nbins=1) 



#creates the scatter plot with a line as a marker
plt.scatter(dataX,dataY,marker="|",s=100000)

And this is the current output:

(https://i.sstatic.net/2fNDiVEM.png)

>Solution :

the necessary changes to make on your code using matplotlib.dates to format the x-axis for hh:mm:

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

now = dt.datetime.now()
x = [now]
y = [0.5]

fig, ax = plt.subplots()
ax.scatter(x, y, marker="|", s=100000)

ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))
ax.xaxis.set_minor_locator(mdates.MinuteLocator(interval=30))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
ax.set_xlim(now.replace(hour=0, minute=0), now.replace(hour=23, minute=59))

plt.ylim(0, 1)
plt.xticks(rotation=45)
plt.show()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading