Display only hours, minutes, and seconds on a chart whose entry is in unix time

2

Be the Python code that generates a bar chart:

# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import matplotlib.dates as dates
from datetime import datetime, timedelta

x = []
y = []
with open("dados.csv") as f:
    for l in f:
        X,Y = l.split(",") #separador eh a virgula
        x.append(float(X))
        y.append(float (Y))

x1 = [datetime.fromtimestamp(int(d)) for d in x]
y_pos = [idx for idx, i in enumerate(y)]

plt.figure(figsize=(17,9))
plt.gca().xaxis.set_major_formatter(dates.DateFormatter(' %H:%M:%S'))

plt.bar(y_pos, y, align='edge', color="blue", alpha=0.5, width=0.5) # <--- EDICAO PRINCIPAL
plt.title("Valores")
plt.ylabel("Numeros")
plt.xlabel('Tempo')
plt.xticks(y_pos, x1, size='small',rotation=35, ha="right")
plt.yticks(y)
plt.ylim(ymax=sorted(y)[-1]+1) # valor maximo do eixo y
#plt.ylim(ymin=sorted(y)[0]-1) # valor minimo do eixo y

plt.show()

The data.csv file, where the first column is in unix time:

1504439700,37438
1504439880,33072
1504439940,576
1504440000,62
1504440060,17731
1504440120,42874
1504440300,59323
1504440360,6601
1504440420,14495
1504440480,8494
1504440540,56293
1504440660,49168
1504440720,11993
1504440780,15700
1504440840,11993
1504440900,7009

The generated graph looks like this:

I would like to display only hour, minute, and second, omitting the day, month, and year. Is it possible?

    
asked by anonymous 03.09.2017 / 19:37

1 answer

3

[TL; DR]

Below is an example with the use of pandas, based on it you can easily adapt your code, it is not mandatory to use pandas, after the example I make a suggestion to adapt your code:

%matplotlib inline
import pandas as pd
import io
import matplotlib.pyplot as plt

s = '''time,data
1504439700,37438
1504439880,33072
1504439940,576
1504440000,62
1504440060,17731
1504440120,42874
1504440300,59323
1504440360,6601
1504440420,14495
1504440480,8494
1504440540,56293
1504440660,49168
1504440720,11993
1504440780,15700
1504440840,11993
1504440900,7009'''

df = pd.read_csv(io.StringIO(s), parse_dates=True)
df.time = pd.to_datetime(df['time'], unit='s').dt.time

df.plot.bar(x=df.time)

Result:

Toadaptyourcodetrychangingthelinewhereyouassignthevaluestothevariablex1sothatitreceivesonlythelast8charactersoftimestamp.Ileaveasuggestionbelow,butIalreadyaddedthat,asIhavenottested,itmaybethatithassomeerroranditdoesnotwork,theideaisjusttopointapath:

x1=[str(datetime.fromtimestamp(int(d)))[-8:]fordinx]

Download or view the code rendered in a jupyter notebook.

    
03.09.2017 / 22:20