Python 绘制累计图(matplotlib)

0 投票
1 回答
2067 浏览
提问于 2025-04-16 05:03

我还没用过matplotlib,但看起来它是用来画图的主要库。我想画一个CPU使用率的图。每分钟我都有后台进程在记录数据(日期、最小负载、平均负载、最大负载)。日期可以是时间戳或者格式化得很好的日期。

我想画一个图,显示最小负载、平均负载和最大负载在同一个图上。在X轴上,我想根据数据量的多少来放分钟、小时、天或者周。

可能会有数据缺口。比如说被监控的进程崩溃了,如果没有人重启它,可能会有几个小时的数据缺失。

我想象中的样子是这样的:http://img714.imageshack.us/img714/2074/infoplot1.png。这个例子没有显示缺口,但在这种情况下,读取的值会变成0。

我现在正在玩matplotlib,也会尝试分享我的结果。这是数据可能的样子:

1254152292;0.07;0.08;0.13
1254152352;0.04;0.05;0.10
1254152412;0.09;0.10;0.17
1254152472;0.28;0.29;0.30
1254152532;0.20;0.20;0.21
1254152592;0.09;0.12;0.15
1254152652;0.09;0.12;0.14
1254152923;0.13;0.12;0.30
1254152983;0.13;0.25;0.32

Or it could look something like this:
Wed Oct 06 08:03:55 CEST 2010;0.25;0.30;0.35
Wed Oct 06 08:03:56 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:57 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:58 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:03:59 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:04:00 CEST 2010;0.00;0.01;0.02
Wed Oct 06 08:04:01 CEST 2010;0.25;0.50;0,75
Wed Oct 06 08:04:02 CEST 2010;0.00;0.01;0.02

-david

1 个回答

2

试试这个:

from matplotlib.dates import strpdate2num, epoch2num
import numpy as np
from pylab import figure, show, cm

datefmt = "%a %b %d %H:%M:%S CEST %Y"
datafile = "cpu.dat"

def parsedate(x):
    global datefmt
    try:
        res = epoch2num( int(x) )
    except:
        try:
            res = strpdate2num(datefmt)(x)
        except:
            print("Cannot parse date ('"+x+"')")
            exit(1)
    return res

# parse data file
t,a,b,c = np.loadtxt(
    datafile, delimiter=';',
    converters={0:parsedate},
    unpack=True)

fig = figure()
ax = fig.add_axes((0.1,0.1,0.7,0.85))
# limit y axis to 0
ax.set_ylim(0);

# colors
colors=['b','g','r']
fill=[(0.5,0.5,1), (0.5,1,0.5), (1,0.5,0.5)]

# plot
for x in [c,b,a]:
    ax.plot_date(t, x, '-', lw=2, color=colors.pop())
    ax.fill_between(t, x, color=fill.pop())

# legend
ax.legend(['max','avg','min'], loc=(1.03,0.4), frameon=False)

fig.autofmt_xdate()
show()

这个代码会从“cpu.dat”文件中读取数据。日期是通过 parsedate 函数来解析的。

Matplotlib 会自动找到最合适的格式来显示 x 轴。

编辑: 添加了图例和填充区域(也许还有更好的方法来实现这个)。

撰写回答