【问题标题】:Plot csv file with readable timestamps?用可读的时间戳绘制 csv 文件?
【发布时间】:2022-01-13 19:05:59
【问题描述】:

我制作了一个 2 通道数据记录器,并希望以“人性化”的方式绘制生成的 csv。 csv文件是这样的:

hh:mm,m,ch1 , ch2 ,--
15:24,0,61.5,66.0
15:25,1,61.1,66.0
15:26,2,60.0,65.0
15:27,3,58.5,63.0
15:29,4,57.7,62.0
15:30,5,57.2,62.0
15:31,6,55.6,60.0
  ...   ...

代码是:

import matplotlib.pyplot as plt
import csv

x = []
y1= []
y2 = []

with open('Documentos/valores2.csv','r') as csvfile:
    lines = csv.reader(csvfile, delimiter=',')
    last = ""
    ini = ""
    for row in lines:
        if len(row) != 4: continue
        if ini =="": ini = row[0]
        if   row[0] == last: 
            continue
        last = row[0]
        x.append(int(ini[:2])+(int(row[1])+int(ini[3:5]) ) /60)
        y1.append(float(row[2]))
        y2.append(float(row[3]))
        
fig, ax = plt.subplots(1, figsize=(8, 6))
fig.suptitle(' Documentos/valores.csv\nde '+ini[:-1]+" a "+last[:-1], fontsize = 14)

ax.plot(x, y1, color="red", label="cantero 1")
ax.plot(x, y2, color="green", label="cantero 2")

plt.legend(loc="lower right", title="", frameon=False)
plt.xlabel('hora')
plt.show()

结果:

我想要小时“1”和“6”而不是小时“25”和“30”......!

【问题讨论】:

    标签: python csv matplotlib


    【解决方案1】:

    您拥有无法更改的横坐标(20、25、30 等),除非您想打破测量顺序,因此您需要更改这些数字的显示方式,为此,您必须使用matplotlib.ticker.FuncFormatter

    当我们这样做时,我建议也使用同一模块中的MultipleLocator,以便小时数像小时一样编号,并引入次要滴答声。

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter, MultipleLocator
    
    # we take the hour, modulo 24, and we format starting with 00
    formatter24 = FuncFormatter(lambda t,_:"%02.2d"%(t%24))
    
    t = np.linspace(15.5, 38, 301)
    y = 12+3*np.sin(6.28*t/20) + t
    
    fig, ax = plt.subplots()
    ax.plot(t, y)
    
    # change the formatters
    ax.xaxis.set_major_formatter(formatter24)
    ax.xaxis.set_major_formatter(formatter24)
    # change the locators
    ax.xaxis.set_major_locator(MultipleLocator(6))
    ax.xaxis.set_minor_locator(MultipleLocator(1))
    # tailor the minor ticks
    ax.xaxis.set_tick_params(which='minor', labelsize=6, colors='gray')
    
    plt.show()
    

    【讨论】:

    • 很好!就我而言,有点概括: t = np.linspace(x[0], x[-1], len(x))
    • @RodolfoLeibner 不!我使用了linspace,因为我不想弄乱真实日期,您必须使用您的x 时间向量。
    • 在这种特殊情况下,x 向量是线性的。
    【解决方案2】:

    用更简单的方式,我们可以格式化向量 x 本身:

    ... ...
    formatter24 = lambda x,n : "%.2f"%(x%24)
    fig, ax = plt.subplots()
    
    ax.xaxis.set_major_locator(MultipleLocator(1))
    ax.xaxis.set_major_formatter(formatter24)
    ax.xaxis.set_minor_locator(MultipleLocator(1/6))
    ax.set_xlim(int(x[0]), 1+int(x[-1]))
    ... ... 
    

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多