利用matplotlib绘制图形

最近须要对一些数据绘制函数图,由于要求也不是很高,但愿尽快出个图看看,也懒得装什么专门的软件,干脆就用python的绘图包matplotlib来作,方便快捷,画出来的图还不错。下面简单记录一下。python

 

绘制图形主要是两步:1. 准备数据;2. 绘图并显示。如下是代码,可很容易看到每一部分的功能linux

#!/usr/bin/env python
# coding=utf-8

import platform
import matplotlib
from matplotlib.font_manager import *

sysstr = platform.system()
if(sysstr == "Windows"):   # windows下中文字符处理
    myfont = FontProperties(fname='C:\Windows\Fonts\simhei.ttf')  #此处选合适的字体文件
else:   # linux下中文字符处理
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    matplotlib.use('Agg')   #若是在没有安装x11的服务器上,此句可输出图片并保存,不然可能报错
    myfont = FontProperties(fname='/usr/share/fonts/truetype/wqy/wqy-microhei.ttc')  #此处选合适的字体文件
matplotlib.rcParams['axes.unicode_minus'] = False
	
import matplotlib.pyplot as plt
import numpy as np

# 定义用到的变量
timebar = []
absolute = []
basevalue = 1000000.0
index = []
relativeMax = []
period = 30

idx = 0
#将变量从文件读入,并放到合适的变量中
for line in open("pnl.txt",'r'):
    row = line.split('\t')
    timebar.append(int(row[0]))
    value = float(row[2])/basevalue
    absolute.append(value)
    if (idx % period == 0):  #此处将该值进行周期性统计
        index.append(idx)
        relativeMax.append(basevalue-min(absolute))
    idx+=1

#画图
fig1 = plt.figure()
plt.title("曲线",fontproperties=myfont)   #整个坐标图的名称
plt.xlabel('timebar')   #x轴名称
plt.ylabel('absolute')   #y轴名称
plt.plot(timebar,absolute)
fig1.savefig("曲线.png")  #保存图片
plt.show()   #显示图片

#将周期性统计结果写入文件
with open("summary.txt",'w') as summaryFile:
    i = 0
    for idx in index:
        output = "{0},{1:.2%},{2:.2%}\n".format(i,absolute[idx],relativeMax[i])
        summaryFile.write(output)
        i+=1

 

其中,pnl.txt文件的形式以下:windows

1524096000      10000.154785    1010000.154785 
1524182400      2988.606417     1012988.761203
1524268800      -3999.066491    1008989.694711
1524355200      -2212.860282    1006776.834429
...
...
...

 

接下来看一个稍微复杂的例子服务器

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

import os
import numpy as np
import time, datetime
import math
import matplotlib
matplotlib.use('Agg')

#import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdate

"""
此处为准备绘图的数据用的代码,略去
横轴数据为xxx(时间),纵轴数据有三组,分别是y1,y2,y3
如下代码绘制双y轴图形,即不一样曲线采用不一样的y轴标记值
最终每幅图上绘制三条曲线,y1和y2的读数在左边y轴,y3的读数在右边y轴
"""

fig = plt.figure(figsize=(10.24,7.68))  # 设置图片大小为1024x768
x_start = 0
period = datetime.timedelta(days=30)   # 按月绘制图形
for idx in range(0, len(xxx)):
    if (xxx[idx] > xxx[x_start] + period):
        plt.xticks(xxx[x_start:idx-1:int((idx-1-x_start)/10)], rotation=30)   # 设置x轴刻度间隔,而且将其旋转30度,防止挤在一块儿
        ax1 = fig.add_subplot(1,1,1)   # 在同一幅图中增长子图
        ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y/%m/%d'))   # 由于横轴为时间,设置时间显示格式
        ax1.plot(xxx[x_start:idx-1], y1[x_start:idx-1], 'g')
        ax1.plot(xxx[x_start:idx-1], y2[x_start:idx-1], 'b')
        ax1.set_ylabel('y1(green) or y2(blue)')
        
        ax2 = ax1.twinx()   # 绘制双y轴图形的关键
        ax2.plot(xxx[x_start:idx-1], y3[x_start:idx-1], 'r')
        ax2.set_ylabel('y3', color='red')
        filename = resultFile[0:-4] + "_" \
                 + xxx[x_start].strftime("%Y-%m-%d") + ".png"
        fig.savefig(filename)    # 保存图片
        fig.clf()    # 清除图形,从新绘制
        x_start = idx

 

绘制完成的图片以下app

相关文章
相关标签/搜索