API的概念
API是Application Programming Interface的缩写,即应用程序编程接口。它指的是一组访问软件应用程序或操作系统的约定及协议。API允许不同的软件系统之间相互交互,使各系统之间的数据交换和功能调用更加方便和快捷。例如,许多应用程序都提供对外的API,允许其他开发者利用这些API实现与该应用程序的交互。
面向对象主要步骤
- 导入模块
- 创建画布
- 在画布上添加绘图区域
- 准备数据
- 调用绘图方法绘制图表
- 展示图表
一、直方图
#1.导入模块
import matplotlib.pyplot as plt
import numpy as np
#2.创建画布
fig = plt.figure()
#3. 在画布上添加绘图区域
ax = fig.add_subplot(111)
#4. 数据准备
x = np.random.randint(0,100,50) #准备50个随机测试数据
#5.调用绘图方法绘制图表
ax.hist(x, bins=8, histtype='stepfilled' ,edgecolor='k') #在8个统计区间中,计算每个区间出现的频次。 # edgecolor:边缘线条颜色
#6.展示图表
plt.show()
二、饼图
#1.导入模块
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mp1
#2.创建画布
fig = plt.figure()
#3. 在画布上添加绘图区域
ax = fig.add_subplot(111)
#4. 数据准备
x = np.array([200, 500, 100, 1000, 300, 550])
explode_position = [0.1, 0.1, 0.07, 0.1, 0.1, 0.1]
#4.1 设置中文
mp1.rcParams['font.sans-serif'] = ['SimHei']
mp1.rcParams['axes.unicode_minus'] = False
#4.2 外侧文字说明
kinds = ['水电费','网上购物','交通出行','饮食','生活日用','社交']
#5.调用绘图方法绘制图表
ax.pie(x, explode=explode_position, radius=1.5, labels=kinds, autopct='%.2f%%',shadow=True, startangle=145) # explode:扇形或楔形离开圆心的距离 radius:扇形或楔形的半径 labels:标签文本 autopct:小数点后的位数 shadow:表示是否阴影 startangle:起始绘制角度
#6.展示图表
plt.show()
三、散点图
#1.导入模块
import matplotlib.pyplot as plt
import numpy as np
#2.创建画布
fig = plt.figure()
#3. 在画布上添加绘图区域
ax = fig.add_subplot(111)
#4. 数据准备
num = 50
x = np.random.rand(num)
y = np.random.rand(num)
area = (30*np.random.rand(num))**2 #每一个散点的权重
#5.调用绘图方法绘制图表
ax.scatter(x, y, s=area, c='purple', alpha=0.6) #s:大小 c:颜色 alpha:透明度
#6.展示图表
plt.show()
四、误差棒图
季节 | 马尾松 | 樟树 | 杉木 | 桂花 |
春季 | 2.04±0.16 | 1.69±0.27 | 4.65±0.34 | 3.39±0.23 |
夏季 | 1.57±0.08 | 1.61±0.14 | 4.99±0.32 | 2.33±0.23 |
秋季 | 1.63±0.10 | 1.64±0.14 | 4.94±0.29 | 4.10±0.39 |
#1.导入模块
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mp1
#2.创建画布
fig = plt.figure()
#3. 在画布上添加绘图区域
ax = fig.add_subplot(111)
#4. 数据准备
x = np.arange(3)
y1 = np.array([2.04, 1.57, 1.63])
y2 = np.array([1.69, 1.61, 1.64])
y3 = np.array([4.65, 4.99, 4.94])
y4 = np.array([3.39, 2.33, 4.10])
error1 = [0.16, 0.08, 0.10] #指定测量偏差
error2 = [0.27, 0.14, 0.14]
error3 = [0.34, 0.32, 0.29]
error4 = [0.23, 0.23, 0.39]
#4.1 设置中文
mp1.rcParams['font.sans-serif'] = ['SimHei']
mp1.rcParams['axes.unicode_minus'] = False
#5.调用绘图方法绘制图表
bar_width = 0.2 #柱形宽度
ax.bar(x, y1,width=bar_width)
ax.bar(x+width, y2,align='center',tick_label=['春季','夏季','秋季'],width=bar_width)
ax.bar(x+2*width, y3,width=bar_width)
ax.bar(x+3*width, y4,width=bar_width)
ax.errorbar(x,y1,yerr=error1,capsize=3,fmt='k,') #绘制误差棒
ax.errorbar(x+width,y2,yerr=error2,capsize=3,fmt='k,') #xerr,yerr:数据的误差范围
ax.errorbar(x+2*width,y3,yerr=error3,capsize=3,fmt='k,') #capsize:误差棒边界横杆的大小
ax.errorbar(x+3*width,y4,yerr=error4,capsize=3,fmt='k,')
plt.ylabel("细根生物量") #y轴标签
plt.title("4个树种不同季节的细根生物量的误差棒图") #标题标签
#6.展示图表
plt.show()