Matplotlib基本图形之折线图
折线图特点
折线图是用折线将各数据连起来组成的图形
常用来观察数据随时间变化的趋势
例如:股票价格,温度变化,等等
示例代码:
import os import time import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates basedir = os.path.dirname(os.path.abspath(__file__)) resultdir = os.path.join(basedir, 'result') class Create_plot(object): def __init__(self,data1,data2,dst,name='',title='Title',color='r',mark='o',alpha=1): ''' :param data1: x轴使用的数据,一般为列表 :param data2: y轴使用的数据,一般为列表 :param dst: 存放生成图片的文件夹路径 :param name: 图片的名称,默认为当前时间戳 :param title: 图片的标题,默认为Title :param c: 图片的颜色,默认为红色 :param mark: 图片点的形状,默认为圆形 :param alpha: 点的透明度,默认为1,即不透明 ''' self.x = data1 self.y = data2 self.dst = dst self.name = name if name else str(int(time.time())) self.title = title self.color = color self.marker = mark self.alpha = alpha def drew_normal(self): plt.plot( self.x, self.y, color = self.color, marker=self.marker, alpha = self.alpha ) plt.title(self.title) picname = self.name+'.jpg' picdir = os.path.join(self.dst, picname) plt.savefig(picdir) def drew_date(self): plt.plot_date( self.x, self.y, color = self.color, marker=self.marker, alpha = self.alpha, linestyle = '-' ) plt.title(self.title) picname = self.name+'.jpg' picdir = os.path.join(self.dst, picname) plt.savefig(picdir) # plt.show()
绘制基本折线图
temp = [2,4,7,10,11,13,15,18,17,13,10,7] hour = [0,2,4,6,8,10,12,14,16,18,20,22] PIC = Create_plot(hour,temp,resultdir) PIC.drew_normal()
结果如下:
绘制日期格式折线图
money = [100,500,800,600,300] date = ['2018/6/1','2018/7/1','2018/8/1','2018/9/1','2018/10/1'] strconverter = mdates.strpdate2num('%Y/%m/%d') date = [strconverter(x) for x in date] PIC = Create_plot(date, money,resultdir) PIC.drew_date()
结果如下: