pandas 作图 统计_pandas的DataFrame对象利用matplotlib画图

df=pandas.DataFrame()

常见的画图方法如下:

df.plot()

也可以传入参数:df.plot(kind=value)决定画什么类型的图

kind=line 画折线图

kind=bar x轴画矩形图

kind=barh y轴画矩形图

kind=pie 画饼图

kind=scatter 画散点

kind=box 画盒子图

kind=kde 画核密度估计图

或者:

df.plot.line()

df.plot.bar()

df.plot.barh()

df.plot.pie()

df.plot.scatter()

df.plot.box()

df.plot.kde()

pandas读取csv文件绘图

import pandas as pd

import matplotlib.pyplot as plt

filename=r"D:\output\dstat.csv"

df=pd.read_csv(filename,index_col="time",parse_dates=True)

df.index=map(lambda x:x.time(),df.index)

#df.index=df.index.map(lambda x:x.time()) 这种方法在python3中才能使用,不推荐这种写法,推荐map(f,list)写法

df_max=df['cpu'].max()

df_avg=df['cpu'][df['cpu']>0].sum()/len(df['cpu'][df['cpu']>0])

#或者:df_avg=df['cpu'].sum()/len(df['cpu'])

df_avg=round(df_avg,2) #取df_avg的2位有效数字

plt.title(" cpu(%) max;"+str(df_max)+"% avg:"+str(df_avg)+"%")

plt.plot(df)

plt.savefig("D:/png/cpu.png") #将plt的画图保存至图片.png格式

用自己的方法方式再写一遍:

import pandas as pd

import matplotlib.pyplot as plt

df=pd.read_csv('./dstat_cpu.csv')

print(type(df))

#结果:

#print(df.index)

#print(type(df.index[0]))

"""

将time列指定为索引(行索引)后,time列的各值即变为str字符串类型

DatetimeIndex(

['2019-10-17 17:02:27', '2019-10-17 17:02:28',

'2019-10-17 17:02:29', '2019-10-17 17:02:30'],

dtype='datetime64[ns]', name='time', freq=None)

"""

#对used这列的值进行换算单位:G

used=df['used']/(1024*1024)

#画折线图,横轴x参数未传,则默认使用行索引作为横轴,used列作为纵轴

#这样就不用画整个所有的列的折线图来,且这样画图能够使用经过转换的数据

used.plot.line()

'''

或者:

df.plot.line(y="used")

x轴未传,则默认使用行索引作为横轴

但这样画图有个问题:直接使用df的列used原生数据,无法使用转换后的数据

df.plot.line(x="time",y="used")

如果要传入横轴x="time",那么在df=pd.read_csv('./dstat_cpu.csv')读取csv时,便不能将time列作为行索引,否则报错!

'''

plt.rcParams['font.sans-serif']=['SimHei']

plt.title("内存used列使用情况统计")

plt.ylabel('单位:G')

plt.xlabel('时间:time')

plt.show()

自己的方法画图.png

df.plot.line方法画图.png

df.plot.line方法画图2.png

import pandas as pd

import matplotlib.pyplot as plt

file=r"./dstat_test.csv"

df=pd.read_csv(file,index_col="time",parse_dates=True)

'''

指定行索引为time列,否则就默认加上数字0开始作为行索引

parse_dates=True 指定是否解析时间格式,为什么要加呢?

这样画图时,横轴的time才能在横轴上显出时间值,否则无法显示

'''

df.plot.line(y=["usr","sys"])

'''

横轴x参数未传,则默认使用行索引作为横轴,纵轴可以是单个参数也可是一个多个参数组成的列表

注:这里不能传参x="time",因为time列已经在读取csv文件时被指定为行索引,故不能传参x

'''

plt.rcParams['font.sans-serif']=['SimHei']

plt.title("CPU% usr:用户使用占比,sys;系统使用占比")

plt.xlabel("时间")

plt.ylabel("使用CPU占比")

plt.savefig(r"./dstat_test.png")

plt.show()

####################################################################################

或如下方法:

df=pd.read_csv(file)

print(df.head())

结果:

默认是以数字0开始作为行索引

新增一列,取值时原time列去除年月日,只保留时分秒

df['times']=pd.DatetiemIndex(df.time).time

'''

time是DatetimeIndex类的一个属性,如还有date,day,year等

注:

使用pd.DatetiemIndex(df.time),对于df.time该列的值,必须得是标准的年月日时分秒的格式,如:

2020/12/15 10:30:30 、 15/12/2020 10:30:00

'''

print(df.head())

plt.plot.line(x="times",y=["usr","sys"])

'''

为什么这里可以传入x="times"?因为新增的times列并不是行索引,所以可以传入

'''

或:

pd.set_index("times")

'''

这样,times列就被设置为行索引,即不能传入x="times",即默认使用行索引来画图

'''

plt.plot.line(y=["usr","sys"])

plt.rcParams['font.sans-serif']=['SimHei']

plt.title("CPU% usr:用户使用占比,sys;系统使用占比")

plt.xlabel("时间")

plt.ylabel("使用CPU占比")

plt.savefig(r"./dstat_test.png")

plt.show()

usr和sys使用CPU占比.png

import pandas as pd

import matplotlib.pyplot as plt

data={"age":[10,20,30,40],"height":[150,152,172,181]}

index=["2019-05-22","2019-06-23","2019-07-24","2019-08-25"]

index=pd.Index(["2019-05-22","2019-06-23","2019-07-24","2019-08-25"])

df=pd.DataFrame(data=data,index=index)

print(df)

"""

age height

2019-05-22 10 150

2019-06-23 20 152

2019-07-24 30 172

2019-08-25 40 181

"""

如果line()不加参数,则默认以DataFrame的index作为横轴,各列值作为纵轴

lines=df.plot.line()

plt.show()

默认索引作为横轴.png

subplots=True表示每个列值的纵轴单独一个子图显示

lines=df.plot.line(subplots=True)

plt.show()

各列值值单独子图.png

line(x="age",y="height")指定"age"列作为横轴,"height"列作为纵轴

lines=df.plot.line(x="age",y="height")

plt.show()

指定列为坐标轴.png

举例

dstat -tcm --output /tmp/dstat_cpu.csv

"time","usr","sys","idl","wai","hiq","siq","used","buff","cach","free"

17:02:27,0.0,0.0,100.0,0.0,0.0,0.0,582262784.0,110592.0,1218052096.0,128589824.0

17:02:28,0.0,0.0,100.0,0.0,0.0,0.0,582262784.0,110592.0,1218052096.0,128589824.0

17:02:29,0.0,0.0,100.0,0.0,0.0,0.0,582262784.0,110592.0,1218052096.0,128589824.0

17:02:30,0.0,0.0,100.0,0.0,0.0,0.0,582262784.0,110592.0,1218052096.0,128589824.0

统计linux系统的内存使用率,保存至csv文件,pandas读取csv文件后生成DataFrame对象,DataFrame对象利用matplotlib画图成像

import pandas ad pd

cpu=pd.read_csv("./dstat_cpu.csv")

print(cpu)

#y轴也可以指定一个列表,以用来画多个不同的纵轴曲线,如y=["usr","sys","idl"]

cpu_plot=cpu.plot.line(x="time",y=["usr","sys","idl","wai","hiq","siq","used","buff","cach","free"])

plt.show()

cpu使用率.png

cpu_plot=cpu.plot.line(x="time",y="used")

plt.title("cpu %") #给此图命名标签

plt.xlabel("x time") #给x轴命名标签

plt.ylabel("cpu used%") #给y轴命名标签

plt.show()

cpu使用率2.png

cpu=pd.read_csv("./dstat_cpu.csv")

cpu1=cpu['used']/(1024*1024)

cpu2=cpu['time']

cpu3=pd.concat([cpu1,cpu2],axis=1)

print(cpu3)

cpu3.plot.line(x='time',y='used')

结果:

used time

0 561.583313 17:02:27

1 562.477859 17:02:28

2 557.424339 17:02:29

3 553.513321 17:02:30

......

plt.title("cpu %")

plt.xlabel("x time")

plt.ylabel("cpu used%")

plt.show()

dataFrame对象画图.png


版权声明:本文为weixin_42134094原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。