这个程序来源于
http://www.matlabsky.com/thread-11364-1-1.html
经过我的改进,效果更佳.如下图所示:
MATLAB代码如下:
clear;clc;close all;
% 画出"囧"字的两个眉毛和一张嘴
x = -3 : 0.1 : 3;
y = 1 ./ (x .^ 2 - 1);
plot(x, y, 'r', 'LineWidth', 3.5);
hold on;
% 画出"囧"字的方框
plot([-3, 3], [-3, -3], 'r', 'LineWidth', 3.5);
plot([-3, 3], [ 3, 3], 'r', 'LineWidth', 3.5);
plot([-3, -3], [-3, 3], 'r', 'LineWidth', 3.5);
plot([ 3, 3], [-3, 3], 'r', 'LineWidth', 3.5);
% 设定曲线的范围
axis([-3, 3, -3, 3]);
% 让"囧"字四四方方
axis equal;
% 去掉坐标轴
axis off;
% 生成"囧.png"文件
print('囧', '-dpng');
Python代码如下:
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 19:35:13 2020
@author: lihaitao
"""
#%% load
import matplotlib.pyplot as plt
import numpy as np
from numpy import ma
plt.close("all")
#%%
# 画出"囧"字的两个眉毛和一张嘴
x = np.arange(-3.0, 3.0 + 1e-6, 0.1)
x = ma.masked_where(np.abs(x ** 2 - 1) < 1e-6, x)
y = 1 / (x ** 2 - 1)
plt.figure()
plt.plot(x, y, 'r', LineWidth=3.5)
# 画出"囧"字的方框
plt.plot([-3, 3], [-3, -3], 'r', LineWidth=3.5)
plt.plot([-3, 3], [ 3, 3], 'r', LineWidth=3.5)
plt.plot([-3, -3], [-3, 3], 'r', LineWidth=3.5)
plt.plot([ 3, 3], [-3, 3], 'r', LineWidth=3.5)
# 让"囧"字四四方方
plt.axis('equal')
# 设定曲线的范围
plt.axis([-3, 3, -3, 3])
# 去掉坐标轴
plt.axis('off')
# 生成"囧.png"文件
plt.savefig('囧.png')
可以发现:
1 Python的语法(matplotlib库)与MATLAB的语法非常相似
这个绝对不是巧合!
matplotlib有两套语法体系, 一套是OOP语法, 另一套就是命令式的, 而命令式的语法是模仿MATLAB的语法, 目的(我猜测)是为了抢夺MATLAB的用户.
2 "plt.axis([-3, 3, -3, 3])"必须写在"plt.axis('equal')"下面, 而MATLAB的话, 顺序无所谓.
读者可以试一下改变这两个命令的顺序, 看看效果有什么区别.
3 必须借助掩码(mask), 来实现非连续的曲线, 而MATLAB自动实现.
如果删除"x = ma.masked_where(np.abs(x ** 2 - 1) < 1e-6, x)", 看看效果有什么变化:
多了两条"法令纹".
创作不易, 请大家"素质三连": 点赞, 收藏, 分享.