matplotlib库的基本使用
1.导入模块
import numpy as np
import matplotlib.pyplot as plt
2.一元函数作图
# x轴的采样点
x = np.linspace(0,6, 100)
# 通过下面曲线加上噪声生成数据,所以拟合模型就用y了……
y = 2*np.sin(x) + 0.3*x**2
# 画模型的图,plot函数默认画连线图
plt.figure('model')
plt.plot(x, y)
# 一定要加上这句才能让画好的图显示在屏幕上
plt.show()
3.散点图
np.random.seed(42)
x = np.linspace(0,6, 100)
y_data = y + np.random.normal(scale=0.3, size=100)
# figure()指定图表名称
plt.figure('data')
# '.'标明画散点图,每个散点的形状是个圆
plt.plot(x, y_data, '.')
plt.show()
同时可以用scatter函数绘制:
除绘制所需两个列表外,第一个参数(s)为size,第二个(c)为color,第三个(marker)为形状(‘*’为星型)
其中参数size和color除了接受常数外,还接受与x,y相同shape的数组。
def getPicture(filename):
datingDataMat, datingLabels = file2matrix(filename)
normDataSet, ranges, minVals = autoNorm(datingDataMat)
x = normDataSet[:,0]
y = normDataSet[:,1]
plt.figure("classify")
plt.title("classify")
plt.xlabel("Frequent flyer mileage(each year)")
plt.ylabel("Percentage of time spent playing video games")
plt.scatter(x,y,s=20*array(datingLabels),c=array(datingLabels),marker='*')
plt.show()
4.plt的一些函数和参数
# 两个图画一起
plt.figure('data & model')
# 通过'k'指定线的颜色,lw指定线的宽度
# 第三个参数除了颜色也可以指定线形,比如'r--'表示红色虚线
# 更多属性可以参考官网:http://matplotlib.org/api/pyplot_api.html
plt.plot(x, y, 'k', lw=3)
# scatter可以更容易地生成散点图
plt.scatter(x, y_data)
# 将当前figure的图保存到文件result.png
#plt.savefig('result.png')
5.绘制柱状图&饼状图
# 包含了狗,猫和猎豹的最高奔跑速度,还有对应的可视化颜色
speed_map = {
'dog': (48, '#7199cf'),
'cat': (45, '#4fc4aa'),
'cheetah': (120, '#e1a7a2')
}
# 整体图的标题
fig = plt.figure('Bar chart & Pie chart')
# 在整张图上加入一个子图,121的意思是在一个1行2列的子图中的第一张
ax = fig.add_subplot(121)
ax.set_title('Running speed - bar chart')
# 生成x轴每个元素的位置
xticks = np.arange(3)
# 定义柱状图每个柱的宽度
bar_width = 0.5
# 动物名称
animals = speed_map.keys()
# 奔跑速度
speeds = [x[0] for x in speed_map.values()]
# 对应颜色
colors = [x[1] for x in speed_map.values()]
# 画柱状图,横轴是动物标签的位置,纵轴是速度,定义柱的宽度,同时设置柱的边缘为透明
bars = ax.bar(xticks, speeds, width=bar_width, edgecolor='none')
# 设置y轴的标题
ax.set_ylabel('Speed(km/h)')
# x轴每个标签的具体位置,设置为每个柱的中央
ax.set_xticks(xticks+bar_width/2)
# 设置每个标签的名字
ax.set_xticklabels(animals)
# 设置x轴的范围
ax.set_xlim([bar_width/2-0.5, 3-bar_width/2])
# 设置y轴的范围
ax.set_ylim([0, 125])
# 给每个bar分配指定的颜色
for bar, color in zip(bars, colors):
bar.set_color(color)
# 在122位置加入新的图
ax = fig.add_subplot(122)
ax.set_title('Running speed - pie chart')
# 生成同时包含名称和速度的标签
labels = ['{}\n{} km/h'.format(animal, speed) for animal, speed in zip(animals, speeds)]
# 画饼状图,并指定标签和对应颜色
ax.pie(speeds, labels=labels, colors=colors)
plt.show()
6.绘制二元函数
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 定义等高线高度函数
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)
# 数据数目
n = 256
# 定义x, y
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
plt.figure('等高线')
# 生成网格数据
X, Y = np.meshgrid(x, y)
# 填充等高线的颜色, 8是等高线分为几部分
plt.contourf(X, Y, f(X, Y), 8, alpha = 0.75, cmap = plt.cm.hot)
# 绘制等高线
C = plt.contour(X, Y, f(X, Y), 8, colors = 'black')
# 绘制等高线数据
plt.clabel(C, inline = True, fontsize = 10)
# 去除坐标轴
plt.xticks(())
plt.yticks(())
ax = Axes3D(plt.figure('三维图'))
ax.plot_surface(X,Y,f(X,Y),cmap = 'rainbow')
ax.set_xlabel('--x--')
ax.set_ylabel('--y--')
ax.set_zlabel('--z--')
ax.set_title('3D')
plt.show()