Rodolfo Leibner
Rodolfo Leibner

Reputation: 191

Plot csv file with readable timestamps?

I've made a 2-channel datalogger and want to plot the resulting csv in a "human friendly" way. The csv file is like:

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
  ...   ...

And the code is:

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

Resulting: enter image description here

I would like to have hour "1" and "6" instead of hour "25" and "30" ... !

Upvotes: 0

Views: 143

Answers (2)

Rodolfo Leibner
Rodolfo Leibner

Reputation: 191

In a simpler way, we can format the vector x itself:

... ...
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]))
... ... 

Upvotes: 0

gboffi
gboffi

Reputation: 25073

enter image description here

You have those abscissae (20, 25, 30, etc) that you cannot change, unless you want to break the order of measurements, so you need to change the way those numbers are displayed, and to do that you must use matplotlib.ticker.FuncFormatter.

While we are at it, I suggest to use also MultipleLocator from the same module, so that the hours are numbered like hours, and introduce also the minor ticks.

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

Upvotes: 1

Related Questions