numpy和matplotlib (3)
1.matplotlib
import matplotlib as mpl
import matplotlib.pyplot as plt # 常用
最基础的用法
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show() # Jupyter Notebook上不用show()也可以显示出来
支持两条曲线,并设置参数
x = np.linspace(0, 10, 100)
cosy = np.cos(x)
siny = np.sin(x)
plt.plot(x, siny)
plt.plot(x, cosy, color="red", linestyle=':') # color:颜色 linestyle:虚线,……
plt.show()
设置x,y轴的区间和名称
plt.plot(x, siny)
plt.plot(x, cosy, color="red", linestyle='--')
plt.xlim(-5, 15)
plt.ylim(0, 1.5)
# 另一种方法
# plt.axis([-5, 15, 0, 1.5])
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.show()
给曲线添加label
plt.plot(x, siny, label = "sin(x)")
plt.plot(x, cosy, color="red", linestyle='--', label = "cos(x)")
plt.xlim(-5, 15)
plt.ylim(0, 1.5)
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.legend() # 别忘了这句!!
plt.show()
给图添加标题
plt.plot(x, siny, label = "sin(x)")
plt.plot(x, cosy, color="red", linestyle='--', label = "cos(x)")
plt.axis([-1, 11, -2, 2])
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.legend()
plt.title("Welcome to the ML World!")
plt.show()
2.Scatter Plot 散点图 (用于二维特征)
plt.scatter(x, siny)
plt.show()
x = np.random.normal(0, 1, 10000)
y = np.random.normal(0, 1, 10000)
plt.scatter(x, y, alpha=0.1) # alpha:透明度
plt.show()
3.应用实例(鸢尾花数据集)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets # 导入数据集
iris = datasets.load_iris() # 鸢尾花数据
# iris其实是一个dictionary, 可以查看其所有键
iris.keys()
# dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename'])
iris.DESCR # 查看描述
# iris.data 是所有数据,形状(150, 4)
# iris.target 是所有标签,形状(150,)
iris.data.shape
# (150, 4)
iris.target.shape
# (150,)
iris.target_names
# array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
# 可见共有三个种类的鸢尾花,它们的值分别为0,1,2
作图
X = iris.data[:, :2] # 只取前两个特征
plt.scatter(X[:, 0], X[:, 1]) # 画散点图
plt.show()
为了将不同种类的点表示出来,可以设置一些参数
y = iris.target
plt.scatter(X[y == 0, 0], X[y == 0, 1], color="red", marker="o")
plt.scatter(X[y == 1, 0], X[y == 1, 1], color="blue", marker="+")
plt.scatter(X[y == 2, 0], X[y == 2, 1], color="green", marker="x")
plt.show()