脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python之 matplotlib和pandas绘图教程

python之 matplotlib和pandas绘图教程

2021-09-17 00:09layman2016 Python

这篇文章主要介绍了python之 matplotlib和pandas绘图教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

不得不说使用python库matplotlib绘图确实比较丑,但使用起来还算是比较方便,做自己的小小研究可以使用。这里记录一些统计作图方法,包括pandas作图和plt作图。

前提是先导入第三方库吧

?
1
2
3
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

然后以下这两句用于正常显示中文标签什么的。

?
1
2
plt.rcparams['font.sans-serif'] = ['simhei'] # 用来正常显示中文标签
plt.rcparams['axes.unicode_minus'] = false # 用来正常显示负号

当然还有一些最基本的步骤:

?
1
2
3
4
5
6
7
plt.xticks(x,xtk,size=12,rotation=50) #设置字体大小和字体倾斜度
plt.xlabel(u'城市') # x轴标签
plt.ylabel(u'数量')
plt.title(u'朋友所在城市') # 图的名称
plt.legend() # 正常显示标题
plt.show() # 显示图像
plt.close() # 绘图后养成习惯性的关掉

对于pandas中的二维数据框,可以直接作图(series类型),简单的折线图或者曲线图如下:

?
1
2
sdata.plot(color='r', style='-o')
plt.show()

python之 matplotlib和pandas绘图教程

如果没有用pandas,直接作曲线图,可以这样写:

?
1
plot(x,y, color ='blue', linewidth=2.5, linestyle="--")

1,柱状图

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
rects1=plt.bar(           #(x,data) 就是所要画的二维数据
    left=x,           #x 是x坐标轴数据,即每个块的x轴起始位置
    height=data,         #data是y坐标轴的数据,即每个块的y轴高度
    width=[0.1,0.2,0.3],     #每一个块的显示宽度
    bottom=[1,2,3],       #每一个块的底部高度
    color='y',          #块的颜色
    edgecolor='g',        #块的边界颜色
    linewidth=2,         #块的线条宽度
    xerr=1,           #x轴误差bar
    yerr=1,           #y轴误差bar
    ecolor='r',         #误差bar的颜色
    capsize=1,          #误差bar的线条宽度
    orientation='vertical',   #块的方向 (horizontal,vertical)
    align="center",       #块的位置 (center, left, right)
    hold=none
    )
 
plt.show()

2,饼图

?
1
2
3
4
5
6
7
8
9
10
11
12
13
plot2=plt.pie(data,             # 每个饼块的实际数据,如果大于1,会进行归一化,计算percentage
    explode=[0.0,0.1,0.2],        # 每个饼块离中心的距离
    colors=['y','r','g'],        # 每个饼块的颜色
    labels=['women','men','unknown'],  # 每个饼块的标签
    labeldistance=1.2,          # 每个饼块标签到中心的距离
    autopct='%1.1f%%',         # 百分比的显示格式
    pctdistance=0.4,           # 百分比到中心的距离
    shadow=true,             # 每个饼块是否显示阴影
    startangle=0,            # 默认从x轴正半轴逆时针起
    radius=1.0              # 饼块的半径
    )
plt.axis('equal') # 显示为圆形,避免比例压缩为椭圆
plt.show()

3,共享x轴,y轴左右轴标(帕累托分析图)

数据样例如下,名称为va,类型为series,左边为职位名称,右边为数量:

?
1
2
3
4
5
6
7
8
9
10
sales     4140
technical   2720
support    2229
it       1227
product_mng   902
marketing    858
randd      787
accounting   767
hr       739
management   630

作图:

?
1
2
3
4
5
6
7
8
9
10
11
12
fr = pd.series(va.values.cumsum() / va.values.sum())
va.plot(kind='bar')
fr.plot(color='r',secondary_y=true, style='-o')
plt.annotate(format(fr[7], '.2%'), xy=(7, fr[7]), xytext=(7*0.9, fr[7]*0.9),
       arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2')) # 用于注释图形指标
# plt.rcparams['font.sans-serif'] = ['simhei'] # 用来正常显示中文标签
# plt.rcparams['axes.unicode_minus'] = false # 用来正常显示负号
# plt1 = plt.pie(va.values,
#        labels=va.index,
#        autopct='%1.1f%%')
plt.xticks(rotation=50) # 设置字体大小和字体倾斜度
plt.show()

左边为出现的频率,右边为累积百分比(这里数据以降序排列较好,便于直观地观察),效果如下:

python之 matplotlib和pandas绘图教程

在pandas中,曲线图可以直接画,比如data中有多个属性,可以直接使用data.plot()。使用plt,若各个属性需要共用xy轴,那么可以重复plot即可。

4,箱型图

使用pandas画箱型图简单方便,但是注释比较麻烦,可以用annotate添加异常点的注释。若使用之前的数据va,则先创建二维数据框再画图。如果有多个列为数字类型,那么可以画每个列的箱型图,这里只有一列数据,如下:

?
1
2
pd.dataframe(va).boxplot()
plt.show()

python之 matplotlib和pandas绘图教程

使用plt直接进行作图:

?
1
2
plt.boxplot(data,labels=[],
     sym='o',whis=1.5)

其中,data可以是一维的,也可多维,若为多维则lables为每一维度的标签。sym为异常值的形状,whis为调节垂直线段的长度。效果如下:

python之 matplotlib和pandas绘图教程

5,多张图在一张画布中,即多个子图

使用plt:

?
1
2
3
4
plt.subplot(221)
plt.plot(x, y1,'r-', lw=2)
plt.subplot(222)
plt.plot(x,y2)

使用pandas:

?
1
2
data.plot(subplots=true, color=['r','b'], style=['-o','-'])
plt.show()

排版方式有不同,pandas是垂直排列,plt可以自己指定位置。pandas效果如下:

python之 matplotlib和pandas绘图教程

补充:python dataframe 多条件筛选 使用&

我就废话不多说了,大家还是直接看代码吧~

?
1
2
3
4
5
6
7
8
df6
out[42]:
 b c d
0 1 b 10.750
1 3 c 8.875
2 2 t 58.000
3 2 l 57.000
4 3 y 46.000
?
1
df6[(df6.b>1) & (df6.d > 10)]
?
1
2
3
4
5
out[45]:
 b c d
2 2 t 58.0
3 2 l 57.0
4 3 y 46.0

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/layman2016/article/details/79538760

延伸 · 阅读

精彩推荐