Table of Contents
简单的时间折线图
先导入必要的包
导入需要画图的数值csv文件(或者其他类型的文件都可以)
开始画图
如果有需要中文标注的需要加上:mpl.rcParams['font.sans-serif'] = ['SimHei']
否则中文会显示一个小小的长方形
# -*- coding: utf-8 -*-
'''
用模型跑出来的预测值和真实值画出带有时间下标的折线图
Created on September 12, 2019
Revised on October 10, 2019 发现预测值中 有些保存的数值会乱 所以增加了寻找正确的对应数值的代码
author: 阿霖
'''
import matplotlib.pyplot as plt
import numpy as np
import csv
import pandas as pd
import matplotlib.dates as mdates
from datetime import datetime
from pylab import mpl
# 解决中文乱码问题(关于编译格式)
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 时间标注
locator = mdates.MinuteLocator(byminute=[0,30])
locator.MAXTICKS = 1500
# 用pandas导入数据
ann_data = pd.read_csv('./dataset03prediction/ann.csv',header=None)
cnn_data = pd.read_csv('./dataset03prediction/cnn.csv',header=None)
lstm_data = pd.read_csv('./dataset03prediction/lstm.csv',header=None)
elm_data = pd.read_csv('./dataset03prediction/elm.csv',header=None)
画图是用 true(真实值)加上四种模型的结果画的
def fig_1(time, true,ann,cnn,lstm,elm,cityname):
plt.figure(figsize = (20,10)) # 调整图片大小
# plt.ylim(140000,220000)
# y_ticks = np.arange(140000,220000,20000)
# plt.yticks(y_ticks , fontsize = 15)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # 设置时间格式
plt.gca().xaxis.set_major_locator(mdates.MonthLocator())
plt.xticks(pd.date_range("2016-9-1","2018-12-30",freq = "1m"),fontsize = 20)
plt.plot(time, true, color='r', marker='o',linewidth = 3,label='True')
plt.plot(time, ann, color='g', marker='D',label='ANN')
plt.plot(time, cnn, color='y', marker='o',label='CNN')
plt.plot(time, lstm, color='r', marker='D',label='LSTM')
plt.plot(time, elm, color='0.5', marker='o',label='ELM')
plt.legend(fontsize=20)
plt.ylabel('Average housing price ',fontsize=20)
plt.xlabel('Time',fontsize=20)
plt.title("Model prediction comparison",fontsize=20)
#plt.xticks(rotation=90)
plt.gcf().autofmt_xdate() # 自动调整x轴啦!
# 在显示之前保存图片
plt.savefig("./dataset03png/"+cityname + ".png" )
print("save","./dataset03png/"+cityname + ".png" )
plt.show()
要注意装有时间的time的list长度要和画图数值的list长度一致
time里面的元素应该是时间元组
要先保存图片再显示,不然会出现白板的情况
time = []
for i in range(52):
Week = str(i+1)
d = "2018-" + Week + "-0"
date_time = datetime.strptime(d , "%Y-%U-%w")
time.append(date_time)