整理:https://apachecn.gitee.io/ailearning/#/docs/da/081
上面的图看不到,就将代码全部跑了一遍画图
import numpy as np
import matplotlib.pyplot as plt
a=[1,2,3,4]
b=[3,1,5,7]
plt.plot(a,b)
plt.show()
颜色
字符 颜色
'b' 蓝色,blue
'g' 绿色,green
'r' 红色,red
'c' 青色,cyan
'm' 品红,magenta
'y' 黄色,yellow
'k' 黑色,black
'w' 白色,white
形状
字符 类型 字符 类型
'-' 实线 '--' 虚线
'-.' 虚点线 ':' 点线
'.' 点 ',' 像素点
'o' 圆点 'v' 下三角点
'^' 上三角点 '<' 左三角点
'>' 右三角点 '1' 下三叉点
'2' 上三叉点 '3' 左三叉点
'4' 右三叉点 's' 正方点
'p' 五角点 '*' 星形点
'h' 六边形点1 'H' 六边形点2
'+' 加号点 'x' 乘号点
'D' 实心菱形点 'd' 瘦菱形点
'_' 横线点
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.show()
plt.plot([1,2,3,4], [1,4,9,16], 'ro-')
plt.show()
横纵坐标指定范围
plt.plot([1,2,3,4], [1,4,9,16], 'rs')
# 指定 x 轴显示区域为 0-6,y 轴为 0-20
plt.axis([0,6,1,20])
plt.show()
同时画多条线
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--',
t, t**2, 'bs',
t, t**3, 'g^')
plt.show()
x = np.linspace(-np.pi,np.pi)
y = np.sin(x)
plt.plot(x, y, linewidth=2.0, color='c')
plt.show()
设置线条样式
lines = plt.plot(x, y)
# 使用键值对
plt.setp(lines, color='b', linewidth=2.0)
# 或者使用 MATLAB 风格的字符串对
plt.setp(lines, 'color', 'r', 'linewidth', 3.5)
plt.show()
figure
plt.figure(num)
plt.subplot(numrows, numcols, fignum)
# 当 numrows * numcols < 10 时,中间的逗号可以省略,因此 plt.subplot(211) 就相当于 plt.subplot(2,1,1)
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
hist 直方图
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
# 横坐标标题
plt.xlabel('Smarts')
# 纵坐标标题
plt.ylabel('Probability')
# 图标题
plt.title('Histogram of IQ')
# 图示(说明)
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
# 横纵坐标范围
plt.axis([40, 160, 0, 0.03])
# 显示网格线
plt.grid(True)
plt.show()
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()