python实时绘制动态曲线_Python: 实时数据画图,横轴显示时间(分钟),纵轴显示随时间变化的另一个量,怎样做?...

该博客展示了如何利用Python的psutil和matplotlib库实现实时监控并绘制CPU使用率的图表。通过设置定时器更新数据,动态展示用户、nice、系统和空闲时间的占用比例,为系统性能监控提供了一个简单的可视化方案。
摘要由CSDN通过智能技术生成

可以考虑绑定一个时间相关的事件。

如下脚本可以显示cpu的实时使用率。

import psutil as p

import matplotlib.pyplot as plt

import matplotlib.font_manager as font_manager

POINTS = 300

fig,ax = plt.subplots()

ax.set_ylim([0, 100])

ax.set_xlim([0, POINTS])

ax.set_autoscale_on(False)

ax.set_xticks([])

ax.set_yticks(range(0, 101, 10))

ax.grid(True)

user = [None] * POINTS

nice = [None] * POINTS

sys = [None] * POINTS

idle = [None] * POINTS

l_user, = ax.plot(range(POINTS), user, label = 'User %')

l_nice, = ax.plot(range(POINTS), nice, label = 'Nice %')

l_sys, = ax.plot(range(POINTS), sys, label = 'Sys %')

l_idle, = ax.plot(range(POINTS), idle, label = 'Idle %')

ax.legend(loc = 'upper center',

ncol = 4, prop = font_manager.FontProperties(size = 10))

bg = fig.canvas.copy_from_bbox(ax.bbox)

def prepare_cpu_usage():

t = p.cpu_times()

if hasattr(t, 'nice'):

return [t.user, t.nice, t.system, t.idle]

else:

return [t.user, 0, t.system, t.idle]

before = prepare_cpu_usage()

def get_cpu_usage():

global before

now = prepare_cpu_usage()

delta = [now[i] - before[i] for i in range(len(now))]

total = sum(delta)

before = now

return [(100.0*dt)/(total+0.1) for dt in delta]

def OnTimer(ax):

global user,nice,sys,idle,bg

tmp = get_cpu_usage()

user = user[1:] + [tmp[0]]

nice = nice[1:] + [tmp[1]]

sys = sys[1:] + [tmp[2]]

idle = idle[1:] + [tmp[3]]

l_user.set_ydata(user)

l_nice.set_ydata(nice)

l_sys.set_ydata(sys)

l_idle.set_ydata(idle)

ax.draw_artist(l_user)

ax.draw_artist(l_nice)

ax.draw_artist(l_sys)

ax.draw_artist(l_idle)

ax.figure.canvas.draw()

timer = fig.canvas.new_timer(interval=100)

timer.add_callback(OnTimer,ax)

timer.start()

plt.show()

截图如下图所示,

另外可以参考 Matplotlib for python developers ,书中有一个wx与matplotlib结合、根据实时数据绘图的详尽例子。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值