统计作图函数

python的主要作图库是matplotlib,而pandas基于matplotlib并对某些命令进行了简化,因此作图通常是matplotlib和pandas相互结合起来使用。
以下要介绍的统计作图函数如下表所示。

作图函数名作图函数功能所属工具箱
plot()绘制线性二维图、折线图matplotlib/pandas
pie()绘制饼形图matplotlib/pandas
hist()绘制二维条形直方图,可显示数据的分配情形matplotlib/pandas
boxplot()绘制样本数据的箱型图matplotlib/pandas
plot(logy=True)绘制y轴的对数图形pandas
plot(yerr=error)绘制误差条形图pandas

在作图之前,有以下常用代码:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
plt.figure(figsize= (7, 5)) #创建图像区域,制定比例
  1. plot()
    实例:在区间(0,2pi)绘制一条蓝色sin(x)虚线。
import numpy as np
x = np.linspace(0, 2*np.pi, 50)
y = np.sin(x)
plt.title(u'sin(x)函数曲线')
plt.plot(x, y, 'bp--')
plt.savefig(r'sin(x)函数曲线.png')
plt.show()

在这里插入图片描述
2.pie(size) size是一个列表,记录各部分的比例
实例:通过向量[15, 30, 45, 10]画饼图,注上标签。

import matplotlib.pyplot as plt
labels = ['Frogs', 'Hogs', 'Dogs', 'Logs'] #定义标签
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] #每一块的颜色
explode = (0, 0, 0.1, 0) #突出显示,这里仅仅突出显示第三块(即第三块)

plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal') #显示为圆(避免比例压缩为椭圆)
plt.savefig(r'pie()函数曲线.png')
plt.show()

在这里插入图片描述

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randint(1, 13, size=(100, 2)), columns=list('xy'))
df1 = df.groupby(by=['x'])['y'].count()
print(df1)
labels = df1.index #定义标签
sizes = df1.values*100/df1.values.sum()

plt.pie(sizes, labels=labels, autopct='%1.2f%%', shadow=True, startangle=90)
plt.axis('equal') #显示为圆(避免比例压缩为椭圆)
plt.savefig(r'pie()函数曲线.png')
plt.show()

运行结果:

x
1      8
2      8
3      7
4     10
5      7
6      4
7      3
8      9
9     12
10     8
11    16
12     8
Name: y, dtype: int64

在这里插入图片描述

3.hist (绘制二维条形直方图,可显示数据的分布数据)
plt.hist(x,y) x是待绘制直方图的一位数据,y可以是整数,表示均为分为y组;也可以是列表,列表各个数字为分组的边界点(即手动制定分界点)。
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(1000) #1000个服从正态分布的随机数
plt.hist(x, 10)
plt.savefig(r'hist()函数曲线.png')
plt.show()

在这里插入图片描述
4.boxplot
可用plt.boxplot、df.plot(kind=‘box’)两种形式

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randint(50, 100, size=(10, 4)), columns=list('xyzw'))
# df.plot(kind='box')
# plt.show()
plt.boxplot(df.values, labels=df.columns)
plt.savefig(r'box()函数曲线.png')
plt.show()

在这里插入图片描述

参考:《Python数据分析与挖掘实战》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值