- 魔法指令以及导入所需要的包
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
- 散点图的绘制
n = 100
x = np.random.normal(0,1,n)
y = np.random.normal(0,1,n)
S = np.random.rand(n)*100
## 散点图/点图
# c颜色
# s点的大小
# alpha 透明度
plt.scatter(x,y,c='r',s=S,alpha=0.5)
# cmap 渐变色
C = np.random.rand(n)
plt.scatter(x,y,c=C,cmap='BuPu')
- 柱状图
x = np.arange(1,13)
y = np.random.randint(0, 100, 12)
# 柱状图
plt.bar(x,y)
# facecolor 柱体颜色
# edgecolor 边框颜色
plt.bar(x,y,facecolor='g',edgecolor='r')
# 绘制数字标注
for a,b in zip(x,y):
plt.text(a,b,'%d' %b,ha='center',va='bottom')
1/2柱状图
labels = ['N1','N2','N3','N4','N5']
x = np.arange(len(labels))
y1 = np.random.randint(0,100,5)
y2 = np.random.randint(0,100,5)
width = 0.4
plt.bar(x-width/2,y1,width,color='r',label='y1')
plt.bar(x+width/2,y2,width,color='g',label='y2')
plt.xticks(range(5),labels)
plt.legend()
- 饼图
labels = ['dog','cat','othors','brid','fish']
sizes = np.random.randint(0,100,5)
# autopct 定制显示的标签
# shadow是 否显示阴影
# startangle 开始画的角度
# explode 凸显饼图 离中心点的距离 传入列表或元组
explode = (0.12,0.15,0.08,0.07,0.05)
plt.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=True,startangle=90,explode=explode)
- 绘制子图 图中图
3种实现子图的方法
plt.subplots 返回值 fig图像,和ax子图列表
plt.subplot
figure.add_subplot
x = np.linspace(0, 2*np.pi, 200)
y1 = np.sin(x**2)
y2 = x+4
fig, ax = plt.subplots()
ax.plot(x, y1)
# 创建一个1行2列图 用元组接收
# sharex sharey是否共享x,y轴
fig, (ax1,ax2) = plt.subplots(1,2,sharex=True)
ax1.plot(x,y1)
ax2.plot(x,y2)
# 数组接收ax子图列表
fig, axes = plt.subplots(2,2)
axes[0,0].plot(x,y1)
axes[1,1].plot(x,y2)
axes[0,1].plot([1,3],[5,2])
axes[1,0].plot(x,x**2)
figure.add_subplot()
# ax5如果原位置有图 会覆盖掉
fig = plt.figure()
# 大小2x2 第一幅图 以此类推
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
# ax5 = fig.add_subplot(322)
不规则子图
# 不规则子图
import matplotlib.gridspec as gridspec
# 创建9*9 英寸 分辨率是100
fig = plt.figure(figsize=(9,9),dpi=100)
# 将图分为3,3份的网格(gridspec)
G = gridspec.GridSpec(3,3)
# 取第一行三格 类似于切片
ax1 = plt.subplot(G[0,:])
# 取第一列 二三行
ax2 = plt.subplot(G[1:3,0:1])
# 取剩下的
ax3 = plt.subplot(G[1:3,1:3])
# 调整(adjust)表格间的间距 h高度垂直距离 w宽度水平距离
plt.subplots_adjust(hspace=0.5,wspace=0.5)