CUP监测1分钟(60s)的python的matplotlib动态作图

import matplotlib.pyplot as plt 
import psutil
import time

# 第1步,导出通用字体设置
from matplotlib import font_manager 
#第2步,定义字体,引出字体模块和位置
my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/noto/simsun.ttf")

plt.ion()

#定义全局变量
cpu=[]
times=[]
mem=[] #注意是mem=memory=内存
io=[]

#定义函数
def get_info():
    cpu_per=psutil.cpu_percent()
    mem=psutil.virtual_memory()
    mem_used=mem.used
    mem_total=mem.total 
    mem_used_per=(mem_used/mem_total*100)
    io=psutil.disk_io_counters()
    io_cnt=io.read_count+io.write_count

    return cpu_per,mem_used_per,io_cnt

c=0   #设置一个变量
while c<61: #观测一定的数量,停止,可以自定义,原为while True就是死循环
    t=time.strftime("%H:%M:%S",time.localtime())
    cpu_per,mem_used_per,io_cnt=get_info()
    times.append(t)
    cpu.append(cpu_per)
    mem.append(mem_used_per)
    io.append(io_cnt)

    #第1张图:ax1
    ax1=plt.subplot(221) #ax1这个图标的位置:分2行2列,第1行第1个
    ax1.patch.set_facecolor('black')#设置ax区域背景颜色 
    ax1.figure.set_facecolor('pink') #这里设置后,整个图,或之后弹出的图片的,背景颜色都是pink

    plt.plot(times,cpu,label='CPU',color='b')
    #第3步:中文显示:加u和fontproperties=my_font
    plt.ylabel(u'CPU 使用率 %',fontsize=8,fontproperties=my_font,color='red') 
    plt.xticks(rotation=30,fontsize=4)
    plt.yticks(range(0,110,10))
    
    #第2张图:
    ax2=plt.subplot(222) #分2行2列,第1行第2个
    ax2.patch.set_facecolor('black')

    plt.plot(times,mem,label='MEM',color='g')
    plt.ylabel(u'MEM 使用率 %',fontsize=8,fontproperties=my_font,color='red')
    plt.xticks(rotation=30,fontsize=4)
    plt.yticks(range(0,110,10))

    #第3张图:
    ax3=plt.subplot(212) #分2行1列,第2个=第2行的一列
    ax3.patch.set_facecolor('black')
    
    plt.plot(times,io,label='IO',color='y')
    plt.ylabel(u'IO  处理数 %',fontsize=8,fontproperties=my_font,color='red')
    plt.xticks(rotation=30,fontsize=4)
    
    plt.pause(1)

    c+=1 #每次+1
    
plt.ioff()
plt.show()
View Code
原文地址:https://www.cnblogs.com/ysysbky/p/12212436.html