玖叶教程网

前端编程开发入门

Python与Matlab画图的代码对比


使用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]);

运行结果:


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()

运行结果:

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言