[关闭]
@nemos 2017-05-08T11:12:48.000000Z 字数 4931 阅读 1519

matplotliib

ml


参考

文档
画廊

快速入门

  1. import matplotlib.pyplot as plt
  2. import numpy as np

函数式绘图

画布

  1. # 生成数据
  2. x = np.linspace(-1, 1, 50)
  3. y1 = 2 * x + 1
  4. y2 = x ** 2
  5. # 新建画布,一个画布对于了一个窗口
  6. plt.figure()
  7. # 以下绘图操作都会在这个创建的这个画布上呈现
  8. plt.plot(x, y2)
  9. plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
  10. # 显示图像
  11. plt.show()
  12. # 再建一个画布
  13. plt.figure()
  14. # 同理
  15. plt.plot(x, y1)
  16. plt.show()

画布一
image_1bfivb82f16g41j2r8f61srqihd9.png-20.5kB

画布二
image_1bfivbrgg1dphnmd1v3rvqs9ntm.png-16.6kB


坐标

  1. plt.figure()
  2. # 设置坐标范围
  3. plt.xlim((-1, 2))
  4. plt.ylim((-2, 3))
  5. # 设置坐标名称
  6. plt.xlabel('I am x')
  7. plt.ylabel('I am y')
  8. # 刻度设置
  9. new_ticks = np.linspace(-1, 2, 5) # -1到2的五个刻度六个间距
  10. plt.xticks(new_ticks)
  11. plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']) # 文字刻度
  12. # get current axis
  13. ax = plt.gca() # 一个坐标有四个轴
  14. # 获得右坐标轴
  15. ax.spines['right'].set_color('none') # none使其不可见
  16. ax.spines['top'].set_color('none')
  17. # x轴设置成下坐标轴
  18. ax.xaxis.set_ticks_position('bottom')
  19. # 移动坐标轴使其在y=0的位置
  20. ax.spines['bottom'].set_position(('data', 0))

image_1bfj182ba16libvo15outk4bib13.png-22.5kB


图例

  1. # 可以在绘制时指定label
  2. l1, = plt.plot(x, y2, label='linear line')
  3. l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='square line')
  4. # 指定图例的线,标签,和位置
  5. plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')

image_1bfj21plf1meu10jb1jin1ndg1o6i1t.png-29.1kB


注解

  1. # 绘制直线
  2. plt.plot(x, y1)
  3. # 设置要标注的点
  4. x0 = 1
  5. y0 = 2*x0 + 1
  6. # 绘制标注的点
  7. plt.scatter([x0, ], [y0, ], s=50, color='b')
  8. # 到X轴的虚线
  9. plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
  10. # 绘制标注
  11. plt.annotate(
  12. r'$2x+1=%s$' % y0, # 要标注的文字
  13. xytext=(+30, -30), # 文字的的位置
  14. textcoords='offset points', # 文字位置的基准
  15. xy=(x0, y0), # 标注的位置
  16. xycoords='data', # 标注位置的基准
  17. fontsize=16,
  18. arrowprops=dict( # 箭头样式
  19. arrowstyle='->',
  20. connectionstyle="arc3,rad=.2"))
  21. # 绘制文字
  22. plt.text(
  23. -3.7, 3, # 位置
  24. r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$', # 文字
  25. fontdict={'size': 16, 'color': 'r'}) # 字体

image_1bfj342o81qnsmulekqorgqhv2a.png-25.2kB


对象式绘图

  1. from matplotlib.figure import Figure
  2. from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
  3. fig = Figure()
  4. canvas = FigureCanvas(fig)
  5. ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  6. line, = ax.plot([0,1], [0,1])
  7. ax.set_title("a straight line (OO)")
  8. ax.set_xlabel("x value")
  9. ax.set_ylabel("y value")
  10. canvas.print_figure('demo.jpg')

image_1beunek4e51ar221n2ljlsub5m.png-84.6kB

层次说明

注:canvas为画图的引擎,这里的层次指的是逻辑的层次

image_1beun9vlgcnf12ns1t5o1otp1u9um.png-8.8kB

image_1beunc08gsnf1p0s4gkuqq18d413.png-58kB

image_1beuncuh4eh1rmfvevkc411u69.png-20.4kB


进阶说明

散点图

  1. n = 1024 # 数据大小
  2. # 正态分布生成
  3. X = np.random.normal(0, 1, n) # 每一个点的X值
  4. Y = np.random.normal(0, 1, n) # 每一个点的Y值
  5. T = np.arctan2(Y,X) # for color value
  6. plt.scatter(
  7. X, Y,
  8. s=75,
  9. c=T, # 色彩map
  10. alpha=.5) # 透明度
  11. plt.xlim(-1.5, 1.5)
  12. plt.xticks(()) # ignore xticks
  13. plt.ylim(-1.5, 1.5)
  14. plt.yticks(()) # ignore yticks
  15. plt.show()

image_1bfj5b6vt8eain41ldh14omshu2n.png-204.4kB


柱状图

  1. # 数据生成
  2. n = 12
  3. X = np.arange(n)
  4. Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
  5. Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
  6. # 设置颜色和正反向绘图
  7. plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
  8. plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
  9. # 坐标设置
  10. plt.xlim(-.5, n)
  11. plt.xticks(())
  12. plt.ylim(-1.25, 1.25)
  13. plt.yticks(())
  14. # 显示每个柱的数值
  15. for x, y in zip(X, Y1):
  16. # ha: horizontal alignment
  17. # va: vertical alignment
  18. plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
  19. for x, y in zip(X, Y2):
  20. plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
  21. plt.show()

image_1bfj5jo7j6t2l0k181h164t1bc734.png-23.8kB


等高线

  1. # 高度函数
  2. def f(x,y):
  3. return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)
  4. n = 256
  5. x = np.linspace(-3, 3, n)
  6. y = np.linspace(-3, 3, n)
  7. X,Y = np.meshgrid(x, y)i
  8. # 颜色填充
  9. plt.contourf(
  10. X, Y, f(X, Y), # 坐标
  11. 8, # 由等高线分成多少部分
  12. alpha=.75, # 透明度
  13. cmap=plt.cm.hot) # 颜色主题
  14. # 等高线
  15. plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)
  16. # 在线上添加label
  17. plt.clabel(C, inline=True, fontsize=10)
  18. # 去掉坐标
  19. plt.xticks(())
  20. plt.yticks(())

image_1bfjh59391h78nmk1ra319ad176a3h.png-49.7kB


图像

  1. pic = np.array(
  2. [0.313660827978, 0.365348418405, 0.423733120134,
  3. 0.365348418405, 0.439599930621, 0.525083754405,
  4. 0.423733120134, 0.525083754405, 0.651536351379]
  5. ).reshape(3,3)
  6. # 显示图片
  7. plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
  8. # 添加标注
  9. plt.colorbar(shrink=.92)

image_1bfjhjgap1gg5nasfd1gl2kr19.png-17kB


3D图

  1. from mpl_toolkits.mplot3d import Axes3D
  1. fig = plt.figure()
  2. # 添加3D坐标轴
  3. ax = Axes3D(fig)
  4. # 数据生成
  5. X = np.arange(-4, 4, 0.25)
  6. Y = np.arange(-4, 4, 0.25)
  7. # x-y 平面的网格
  8. X, Y = np.meshgrid(X, Y)
  9. R = np.sqrt(X ** 2 + Y ** 2)
  10. Z = np.sin(R)
  11. # 生成曲面
  12. ax.plot_surface(
  13. X, Y, Z,
  14. rstride=1, # row栅格的跨度
  15. cstride=1, # column同上
  16. cmap=plt.get_cmap('rainbow')) # 色彩主题
  17. ax.contourf(
  18. X, Y, Z,
  19. zdir='z', # 指定从Z轴的投影
  20. offset=-2,
  21. cmap=plt.get_cmap('rainbow'))
  22. plt.show()

子画布

  1. plt.figure()
  2. # 创建子画布
  3. plt.subplot(2,2,1) # 画第一个子画布
  4. plt.plot([0,1],[0,1])
  5. plt.subplot(2,2,2) # 画第二个子画布
  6. plt.plot([0,1],[0,2])
  7. plt.subplot(223)
  8. plt.plot([0,1],[0,3])
  9. plt.subplot(224)
  10. plt.plot([0,1],[0,4])
  11. plt.show()

image_1bfjr8kldjk1hvt7b218p09i39.png-39.3kB

  1. plt.figure()
  2. # 创建子画布
  3. plt.subplot(2,1,1) # 使第一个画布占满第一行的三列
  4. plt.plot([0,1],[0,1])
  5. plt.subplot(2,3,4) # 从第四个格子开始排
  6. plt.plot([0,1],[0,2])
  7. plt.subplot(235)
  8. plt.plot([0,1],[0,3])
  9. plt.subplot(236)
  10. plt.plot([0,1],[0,4])
  11. plt.show()

image_1bfjrc7uv192j1c6n1ssm9c814rjm.png-38.3kB


图中图

  1. fig = plt.figure()
  2. x = [1, 2, 3, 4, 5, 6, 7]
  3. y = [1, 3, 4, 2, 5, 8, 6]
  4. # 绘制大图
  5. left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
  6. ax1 = fig.add_axes([left, bottom, width, height])
  7. ax1.plot(x, y, 'r')
  8. ax1.set_xlabel('x')
  9. ax1.set_ylabel('y')
  10. ax1.set_title('title')
  11. # 绘制小图
  12. left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
  13. ax2 = fig.add_axes([left, bottom, width, height])
  14. ax2.plot(y, x, 'b')
  15. ax2.set_xlabel('x')
  16. ax2.set_ylabel('y')
  17. ax2.set_title('title inside 1')

动画

  1. from matplotlib import animation
  1. fig, ax = plt.subplots()
  2. # 生成正弦曲线
  3. x = np.arange(0, 2*np.pi, 0.01)
  4. line, = ax.plot(x, np.sin(x))
  5. # 定义动画函数,接受一个帧数参数
  6. def animate(i):
  7. line.set_ydata(np.sin(x + i/10.0))
  8. return line,
  9. # 开始帧
  10. def init():
  11. line.set_ydata(np.sin(x))
  12. return line,
  13. ani = animation.FuncAnimation(
  14. fig=fig, # 指定figure
  15. func=animate, # 动画函数
  16. frames=100, # 动画长度
  17. init_func=init, # 开始帧
  18. interval=20, # 更新频率,ms为单位
  19. blit=False) # mac用false
  20. plt.show()
  21. # 保存动画
  22. anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

引用

莫烦python-Matplotlib
绘图: matplotlib核心剖析
matplotlib - 2D and 3D plotting in Python
利用plotly for Python进行数据可视化


添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注