如何在csv图表中删除年份

时间:2019-08-26 06:53:27

标签: python python-3.x csv datetime matplotlib

我编写了一个python程序,将csv文件转换为图表。 它在图表中显示了1900,但我不需要它。 请帮助我检查问题出在哪里。 谢谢。

import csv
from matplotlib import pyplot as plt
from datetime import datetime
filename='/home/pi/env_watcher/temp/env_report.csv'
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)
    dates,ttemps,ctemps,thumis,chumis=[],[],[],[],[]
    for row in reader:
        current_date=datetime.strptime(row[0],'%b %d %H:%M:%S')
        dates.append(current_date)
        ttemp=float(row[1])
        ttemps.append(ttemp)
        ctemp=float(row[2])
        ctemps.append(ctemp)
        thumi=float(row[3])
        thumis.append(thumi)
        chumi=float(row[4])
        chumis.append(chumi)

fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,thumis,c='red',alpha=0.5)
plt.plot(dates,chumis,c='blue',alpha=0.5)
plt.title('Weekly Humidity',fontsize=24)
plt.xlabel('',fontsize=16)
plt.ylabel('Humidity(%)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
fig.autofmt_xdate()
plt.savefig("/home/pi/env_watcher/temp/env_humi.png")
plt.show()

csv文件内容如下
......
8月25日05:10:13,30,26.8,70,45.0
8月25日05:20:13,30,26.8,70,44.8
8月25日05:30:15,30,26.8,70,45.5
8月25日05:40:13,30,26.8,70,45.5
8月25日05:50:13,30,26.9,70,46.1
8月25日06:00:13,30,26.9,70,46.3
8月25日06:10:13,30,26.9,70,46.8
8月25日06:20:13,30,26.9,70,46.8
......

输出: enter image description here

2 个答案:

答案 0 :(得分:0)

看起来您不需要此处的转换。只需使用

for row in reader:
    current_date=row[0]

或者如果您只需要日期和月份 使用:

current_date=datetime.strptime("Aug 25 05:10:13",'%b %d %H:%M:%S').strftime("%m-%d")

答案 1 :(得分:0)

根据需要在xaxis上使用set_major_formatter()设置日期格式:

import csv
from matplotlib import pyplot as plt
from datetime import datetime
import matplotlib.dates as mdates

filename = '/home/pi/env_watcher/temp/env_report.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)
    dates, ttemps, ctemps, thumis, chumis = [], [], [], [], []
    for row in reader:
        current_date = datetime.strptime(row[0], '%b %d %H:%M:%S')
        dates.append(current_date)
        ttemp = float(row[1])
        ttemps.append(ttemp)
        ctemp = float(row[2])
        ctemps.append(ctemp)
        thumi = float(row[3])
        thumis.append(thumi)
        chumi = float(row[4])
        chumis.append(chumi)

fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, thumis, c='red', alpha=0.5)
plt.plot(dates, chumis, c='blue', alpha=0.5)
plt.title('Weekly Humidity', fontsize=24)
plt.xlabel('', fontsize=16)
plt.ylabel('Humidity(%)', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
fig.axes[0].xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))  # Won't show year
fig.autofmt_xdate()
plt.savefig("/home/pi/env_watcher/temp/env_humi.png")
plt.show()