matplotlib是python比较底层的可视化库,可定制性强、图表资源丰富、简单易用、达到出版质量级别。
导入模块
import matplotlib.pyplot as plt
创建画板
figure = plt.figure(figsize=(10, 10))
创建子图(画纸)
参数(2,1,1)代表将画板分为2行1列,第1个
参数(2,1,2)代表将画板分为2行1列,第2个
ax1 = plt.subplot(2, 1, 1)
ax2 = plt.subplot(2, 1, 2)
绘制
polt代表折线图,marker表示点的形状,linestyle线段的形状
legend表示显示图例,也就是图形里的内容
ax.plot(x, y, color='red', marker='*', linestyle='-.')
plt.legend()
单图:
# 1.导入绘图库
import matplotlib.pyplot as plt
import numpy as np
# 2.创建画板figure
figure = plt.figure(figsize=(10, 10))
# 3. 创建子图subplot/Axes 画纸
# 1行1列第1个
ax = plt.subplot(1, 1, 1)
# 4. 准备数据
# 从0~50分成100份
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 5. 绘制
ax.plot(x, y, color='red', marker='*', linestyle='-.')
ax.set_title('y = sinx')
ax.set_xlabel ('x')
ax.set_ylabel ('y')
#6. 显示图像
plt.show()
运行结果:
其实因为只有一个图,所以可以不用创建子图,直接在画板上作图:
# 导入绘图库
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
# 1. 准备数据
x = np.linspace(0, 10, 100)
y = np.sin(x)
#2. 画板里只有一个图,可以直接绘图
plt.plot(x, y)
plt.title('y = sinx')
plt.xlabel ('x')
plt.ylabel ('y')
plt.show()
多图:
# 1.导入绘图库
import matplotlib.pyplot as plt
import numpy as np
# 2.创建画板figure
figure = plt.figure(figsize=(10, 10))
# 3. 创建子图subplot/Axes 画纸
# 生成2行1列的子图:1行1列:sinx 2行1列:cosx
ax1 = plt.subplot(2, 1, 1) # 第一个
ax2 = plt.subplot(2, 1, 2) # 第二个
# 4. 准备数据
# 从0~50分成100份
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# 5. 绘制
ax1.plot(x, y1, color='red', marker='*', linestyle='-.')
ax1.set_title('y = sinx')
ax1.set_xlabel ('x')
ax1.set_ylabel ('y')
ax2.plot(x, y2, color='yellow', marker='o', linestyle='-.')
ax2.set_title('y = cosx')
ax2.set_xlabel ('x')
ax2.set_ylabel ('y')
#6. 显示图像
plt.show()
怎么实现一定范围内震动呢?y加个随机数
import matplotlib.pyplot as plt
import numpy as np
def trans(x):
# 随机数范围 -5 ~ 5; x.shape x的长度50 50个0~1的数字
random_data = -5 + 10 * np.random.random(x.shape)
# y加了一个随机数
y = 1 / 100 * x ** 4 - 8 / 300 * x ** 3 - 3 + np.log(x) + random_data
return y
if __name__ == '__main__':
x = np.linspace(-10, 10, 50)
y = trans(x)
# 散点图
# plt.scatter(x, y, marker='x', color='g')
# plt.show()
# 曲线图
plt.plot(x, y, marker='x', color='g',label = 'y=1/100x^4-8/300x^3-3+ln(x)')
plt.legend() # 加上图例,就是显示label
plt.show()
条形图(bar chart),也称为柱状图,是一种以长方形的长度为变量的统计图表,长方形的长度与它所对应的变量数值呈一定比例
下面是一个关于男生女生购买饮用水的调查结果:
import matplotlib.pyplot as plt
import numpy as np
# 解决中文乱码
plt.rcParams['font.sans-serif']= ['SimHei']
# 创建画板
figure = plt.figure()
# 创建子图 1行2列
ax1 = plt.subplot(1, 2, 1)
ax1.set_title('男生购买情况')
ax2 = plt.subplot(1, 2, 2)
ax2.set_title('女生购买情况')
# 数据信息
waters = ['碳酸饮料','奶茶','矿泉水','茶']
boy_num = [6, 3, 9, 10]
girl_num = [7, 8, 5, 7]
# 绘制条形图
ax1.bar(waters, boy_num, width=0.4, color='y')
# 横向的条形图
# ax1.barh(waters, boy_num, height=0.4, color='o')
ax2.bar(waters, girl_num, width=0.4, color='g')
plt.show()
# plt.savefig('bar.png') #保存
# 解决中文乱码
plt.rcParams['font.sans-serif']= ['SimHei']
想要绘制横向的条形图:
# 横向的条形图
ax1.barh(waters, boy_num, height=0.4, color='o')
保存:
plt.savefig('bar.png')
如果将男生女生的数据放在一个图中,则绘制并列的柱状图:
import matplotlib.pyplot as plt
import numpy as np
# 中文乱码
plt.rcParams['font.sans-serif']= ['SimHei']
# 数据信息
waters = ['碳酸饮料','奶茶','矿泉水','茶']
boy_num = [6, 3, 9, 10]
girl_num = [7, 8, 5, 7]
# 调整条形图的横坐标
bar_width=0.4
boy_index = np.arange(len(waters)) # [0,1,2,3]
girl_index = boy_index + bar_width # [0.4,1.4,2.4,3.4] np的传播机制,自动加起来
# 绘制条形图
plt.bar(boy_index, boy_num, bar_width, color='y', label='男生')
plt.bar(girl_index, girl_num, bar_width, color='g', label='女生')
plt.legend()
# 修改无意义的横坐标为有意义的
plt.xticks(boy_index + bar_width/2, waters) # 位置,文字
plt.title('购买饮水情况的调查结果')
plt.ylabel('购买量')
plt.show()
运行结果:
官方网址: https://seaborn.pydata.org/introduction.html
Seaborn共提供5种主题风格,分别为darkgrid、whitegrid、dark、 white以及ticks。利用set()和set_style()两个函数对整体风格进行控制
安装seaborn
pip install -i https://pypi.douban.com/simple seaborn
mport matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
x = np.linspace(0, 10, 100)
y = np.sin(x)
# 设置seaborn主题样式
sns.set(style='ticks')
plt.plot(x, y)
plt.title('y = sinx')
plt.xlabel ('x')
plt.ylabel ('y')
#去掉上边框和右边框 在绘图之后进行设置
sns.despine(top=True, right=True)
plt.show()
# 1.导入绘图库
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
figure = plt.figure(figsize=(10, 10))
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# 5. 绘制,子图选择不同风格
with sns.axes_style(style='dark'):
ax1 = plt.subplot(2, 1, 1)
ax1.plot(x, y1, color='red', marker='*', linestyle='-.')
ax1.set_title('y = sinx')
ax1.set_xlabel ('x')
ax1.set_ylabel ('y')
with sns.axes_style(style='darkgrid'):
ax2 = plt.subplot(2, 1, 2)
ax2.plot(x, y2, color='yellow', marker='o', linestyle='-.')
ax2.set_title('y = cosx')
ax2.set_xlabel ('x')
ax2.set_ylabel ('y')
plt.show()
原理:
K近邻算法: 近朱者赤,近墨者黑。新的数据点离谁(一个或多个近邻点)最近, 就和谁属于同一类。
在skilit-learn中内置了若干个玩具数据集(Toy Datasets), 还有一些API可以自己动手生成数据集
生成一系列数据集当作机器学习的训练数据集后,接下来就是根据KNN算法找一个模型, 然后根据模型对未知数据进行分类。
# K近邻算法可以用来做分类
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
# 创建K近邻分类的数据集 (训练集)
# random_state=8:随机种子:保证每次随机生成的样本信息一致
# 样本数 几个特征 根据特征分几类 随机种子
# X特征 y第几类
X, y= make_blobs(n_samples=200, n_features=2, centers=2, random_state=8)
# # 给定一个新的特征信息,分析它属于哪一类
# test_data = [6, 4.82]
#
# plt.scatter(X[:, 0], X[:, 1], edgecolors='yellow', color='white') # 所有,第一列 所有,第二列
# plt.scatter(test_data[0], test_data[1], marker='*', color='r')
# plt.show()
# 如何去寻找一个模型,根据模型判断测试数据属于哪一类
# 机器学习:寻找一个函数/模型的过程
#K近邻分类的对象
clf = KNeighborsClassifier()
# 训练,拟合,找模型的过程
clf.fit(X, y)
test_data = [6, 3] # 测试集:测试模型正确率的数据集
# 进行预测
class_name = clf.predict([test_data]) # 会很多数据,用列表,这里只有一个
print('新数据点的分类是:',class_name)
K近邻算法也可以用于回归, 原理和分类相同。 计算每个数据点的预测值时,模型会选择离该数据点最近的若干个点,并将它们的y值取平均值,并作为新数据点的预测值。
from sklearn.datasets import make_regression
from sklearn.neighbors import KNeighborsRegressor
import matplotlib.pyplot as plt
import numpy as np
# 解决中文乱码
plt.rcParams['font.sans-serif']= ['SimHei']
plt.rcParams['axes.unicode_minus'] = False # 有负数时
# 产生回归的数据集(训练集)
# 特征,y值
# n_features=1,n_informative=1: 也是一些特征 noise=50:算是误差吧 噪声
X, y = make_regression(n_samples=100, n_features=1,n_informative=1, noise=50, random_state=8)
# 通过K近邻的回归器寻找模型
reg = KNeighborsRegressor()
reg.fit(X,y)
# 给定一些新的数据,预测y值(测试集)
# np.linspace(-3, 3, 100) # 一维的
test_x = np.linspace(-3, 3, 100).reshape(-1, 1) # 生成n行1列
# reg.predict([[1],[2]]) # 预测时需要传递的 二维
test_y = reg.predict(test_x)
print('准确度:', reg.score(X, y))
# 绘制图形
plt.scatter(X, y, marker='*', color='orange', edgecolors='black', label='训练集')
plt.plot(test_x, test_y, color='black', label='测试集')
plt.title('KNN Regressor')
plt.legend()
plt.show()