1

I want to format my x-axis in the way "%H:%M" but with continuous hours (e.g. 2 days = 48:00) like in this example:

How I want it

How I want it

The closest attempt I could made is this example:

How it is

How it is But the hours doesn't continue. Here is my simple Code snippet:

import matplotlib.pyplot as plt
import matplotlib.dates as md
import numpy as np

dataY = np.array([0,1,2,3,4,5,6,7,8,9])
dataX = np.array([0.1,0.5,0.8,1.2,1.3,1.6,1.9,2.1,2.2,2.5]) #Time values like in Excel 1h = 1/24

dataX = dataX +1 #Otherwise it says Error, time values <1
fig, ax = plt.subplots()
timeformat = md.DateFormatter('%H:%M')
plt.Axes.format_xdata = timeformat
ax.xaxis_date()
ax.xaxis.set_major_formatter(timeformat)
plt.xlim(1,4)

plt.plot(dataX,dataY)
plt.ylabel('Y-Values')
plt.xlabel('Time [hh:mm]')

plt.show()

Many thanks in advance

1 Answer 1

2

You are not plotting any actual dates here. It hence makes sense to not try to format those values as dates. Instead, plot the numbers as they are and use your custom format of choice.

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np

dataY = np.array([0,1,2,3,4,5,6,7,8,9])
dataX = np.array([0.1,0.5,0.8,1.2,1.3,1.6,1.9,2.1,2.2,2.5]) #Time values 1h = 1/24

fig, ax = plt.subplots()

def timeformat(x,pos=None):
    h = int(x*24.)
    m = int((x*24.-h)*60)
    return "{:02d}:{:02d}".format(h,m)

ax.xaxis.set_major_formatter(mticker.FuncFormatter(timeformat))

plt.plot(dataX,dataY)
plt.ylabel('Y-Values')
plt.xlabel('Time [hh:mm]')

plt.show()

enter image description here

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

1 Comment

Great! Thanks for the fast reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.