0

I am trying to plot a tensor of shape (x, 88, 1) where x is on the order of ~10,000. Each value at x is a point in time at an interval of .028 seconds.

How can I plot the values of x as a time in minutes:seconds with matplotlib? Currently my graphs come out like

enter image description here

example code

    plt.imshow(missing, aspect='auto', origin='lower', cmap='gray_r', vmin=0, vmax=1)
    plt.figure(1, figsize=(8.5, 11))
    plt.xlabel('Sample #')
    plt.colorbar()
    plt.clf()

Google keeps producing results plotting dates which is not what I need so I'm asking here.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
JME
  • 2,293
  • 9
  • 36
  • 56

2 Answers2

2

You may first set the extent of the image to the range of seconds your data covers. You can then format the seconds as minutes:seconds using a FuncFormatter. You may then set the locations of the ticks to nice numbers, e.g. 30 seconds intervals.

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

data = np.random.rand(88, 10000)

interval = .028  # seconds
extent = [0, data.shape[1]*interval, 0, data.shape[0]]

plt.imshow(data, extent=extent, aspect='auto', origin='lower', 
           cmap='gray_r', vmin=0, vmax=1)

# Format the seconds on the axis as min:sec
def fmtsec(x,pos):
    return "{:02d}:{:02d}".format(int(x//60), int(x%60)) 
plt.gca().xaxis.set_major_formatter(mticker.FuncFormatter(fmtsec))
# Use nice tick positions as multiples of 30 seconds
plt.gca().xaxis.set_major_locator(mticker.MultipleLocator(30))

plt.xlabel('Time')
plt.colorbar()
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

Plots and Images with datetimes on the x-axis

If the x-axis is set as a datetime number at the beginning, the custom function to format %M:%S is not required. Both solutions are similar to Dates in the xaxis for a matplotlib plot with imshow.

Imports:

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

x-axis:

x = [dt.datetime(2018, 9, 30, 0, 0, 0, 0) + dt.timedelta(seconds=(0.028 * 10000 * x)) for x in range(0, 2)]
x = mdates.date2num(x)

y-axis:

y = np.random.rand(88, 10000)

Plot:

plt.imshow(y, extent=[x[0], x[1], 0, 87], aspect='auto', origin='lower', cmap='gray_r', vmin=0, vmax=1)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%M:%S'))
plt.gcf().autofmt_xdate()
plt.colorbar()
plt.xlabel('Time: (min:sec)')
plt.title('Tensor Plot')
plt.show()

Figure:

Tensor Plot

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158