Search code examples
pythonmatplotlibplottimeoverlap

Matplotlib x-axis overlapping using time string


I want to create a plot from the following data:

timeArray= ['11:47:46.585', '11:47:46.695', '11:47:46.805', '11:47:46.915', '11:47:47.025', '11:47:47.135', '11:47:47.245', '11:47:47.355', '11:47:47.465', '11:47:47.575', '11:47:47.685', '11:47:47.795', '11:47:47.905', '11:47:48.015', '11:47:48.125', '11:47:48.235', '11:47:48.345', '11:47:48.455', '11:47:48.565', '11:47:48.675', '11:47:48.785', '11:47:48.895', '11:47:49.005', '11:47:49.115', '11:47:49.225', '11:47:49.335', '11:47:49.445', '11:47:49.555', '11:47:49.665', '11:47:49.775', '11:47:49.885', '11:47:49.995', '11:47:50.105', '11:47:50.215', '11:47:50.325', '11:47:50.435', '11:47:50.545', '11:47:50.655', '11:47:50.765', '11:47:50.875', '11:47:50.985', '11:47:51.095', '11:47:51.205', '11:47:51.315', '11:47:51.425', '11:47:51.535', '11:47:51.645', '11:47:51.755', '11:47:51.865', '11:47:51.975', '11:47:52.085', '11:47:52.195', '11:47:52.305', '11:47:52.415']

valueArray = [10382.0, 8372.0, 11117.0, 11804.0, 10164.0, 10221.0, 10488.0, 7910.0, 12911.0, 11422.0, 15361.0, 15424.0, 10629.0, 14993.0, 13827.0, 15164.0, 10514.0, 10356.0, 14638.0, 12272.0, 14980.0, 14391.0, 12984.0, 18967.0, 15792.0, 14753.0, 16205.0, 19187.0, 13922.0, 10787.0, 14500.0, 12918.0, 13985.0, 14695.0, 14014.0, 12087.0, 12163.0, 11424.0, 8598.0, 8573.0, 9986.0, 10315.0, 11449.0, 9146.0, 11160.0, 6861.0, 10211.0, 9097.0, 8443.0, 5446.0, 6354.0, 6829.0, 5786.0, 7860.0]

timeArray will be x-axis, valueArray will be y-axis.

plot line looks like this:

import matplotlib.pyplot as plt
plt.plot(timeArray,valueArray,'r', label='values over time')

And I'm getting this graph:

overlap time axis

I have used: plt.gcf().autofmt_xdate(), but still getting one time over the next.

I have also tried:

xaxis = np.linspace(min(timeArray),max(timeArray), 10)
plt.xticks(xaxis) 

but i got a typeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')

Is there a simple way to keep the data as it is but without showing every single time with microseconds?


Solution

  • I'd suggest you convert your times to datetime objects rather than strings, and then use matplotlib.mdates.DateFormatter() with an appropriate date format:

    import matplotlib.dates as mdates
    import datetime
    
    fmt = mdates.DateFormatter('%H:%M:%S')
    timeArray = [datetime.datetime.strptime(i, '%H:%M:%S.%f') for i in timeArray]
    
    fig, ax = plt.subplots()
    
    plt.plot(timeArray,valueArray,'r', label='values over time')
    ax.xaxis.set_major_formatter(fmt)
    

    The result:

    enter image description here