【问题标题】:Plotting an image with x-axis as time以 x 轴为时间绘制图像
【发布时间】:2019-03-05 13:16:48
【问题描述】:

我正在尝试绘制形状为 (x, 88, 1) 的张量,其中 x 约为 10,000。 x 处的每个值都是间隔为 0.028 秒的时间点。

如何使用 matplotlib 将 x 的值绘制为以分钟为单位的时间:秒?目前我的图表像

示例代码

    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 不断产生结果绘制日期,这不是我需要的,所以我在这里问。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    Plots and Images with datetimes on the x-axis

    如果 x 轴在开头设置为日期时间数字,则不需要格式化 %M:%S 的自定义函数。两种解决方案都类似于Dates in the xaxis for a matplotlib plot with imshow

    进口:

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

    x 轴:

    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 轴:

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

    剧情:

    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()
    

    图:

    【讨论】:

      【解决方案2】:

      您可以先将图像的范围设置为数据覆盖的秒数范围。然后,您可以使用FuncFormatter 将秒格式化为分:秒。然后,您可以将刻度的位置设置为漂亮的数字,例如30 秒间隔。

      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()
      

      【讨论】:

        猜你喜欢
        • 2011-06-15
        • 2020-09-18
        • 2016-06-24
        • 2021-09-27
        • 2016-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-01
        相关资源
        最近更新 更多