使用Matlab进行数据分析,经常需要用到plot命令将数据可视化。
Python提供一个非常好用的库:Matplotlib(Python 2D绘图库),它提供了类似matlab的画图接口,包括:

  • figure:图像的窗口,即画图区域;
  • plot:画图命令;
  • title:创建标题;
  • legend:创建图例;
  • text:在图上添加描述性的文字;
  • grid:控制网格显示;
  • xlabel:x坐标轴;
  • ylabel:y坐标轴;
  • xlim:调整x坐标轴范围;
  • ylim:调整y坐标轴范围。
比如在一个figure里同时画出sin曲线和cos曲线。Matlab代码和Python代码分别如下:

1、Matlab代码
%% figure 的构成要素
  • x = 0 : 0.2 : 8.0;
  • y1 = sin(x);
  • y2 = cos(x);
  • figure(3);
  • plot(x, y1, 'rx-');
  • hold on
  • plot(x, y2, 'bo-')
  • hold off
  • title('Trigonometric Function', 'fontsize', 20);
  • legend({'sin', 'cos'}, 'fontsize', 15);
  • text(1.6, 0.5, 'y > 0', 'fontsize', 18);
  • grid on
  • xlabel('x', 'fontsize', 18);
  • ylabel('y', 'fontsize', 18);
  • xlim([0 6.3]);
  • ylim([-1.2 1.2]);
  • 复制代码
    运行结果:
    bab6898f6f63499a8807457d95415eff~noop.image?_iz=58558&from=article.jpg



    2、Python代码
    #!/usr/bin/python
  • # -*- coding: utf-8 -*-
  • import numpy as np
  • import matplotlib.pyplot as plt
  • x = np.arange(0.0, 8.0, 0.2)
  • y1 = np.sin(x)
  • y2 = np.cos(x)
  • plt.figure(3)
  • plt.plot(x, y1, 'rx-')
  • plt.plot(x, y2, 'bo-')
  • plt.title('Trigonometric Function', fontsize=20)
  • plt.legend(['sin', 'cos'], fontsize=15)
  • plt.text(1.6, 0.5, 'y > 0', fontsize=18)
  • plt.grid()
  • plt.xlabel('x', fontsize=18)
  • plt.ylabel('y', fontsize=18)
  • plt.xlim(0, 6.3)
  • plt.ylim(-1.2, 1.2)
  • plt.show()
  • 复制代码
    运行结果:
    52efe7284c9f409f825d4ea37c06bfe6~noop.image?_iz=58558&from=article.jpg

    来源:算法集市