python自用速查

plt

直线

1
2
plt.axhline(y=yn, linestyle='--', label=f'pe={yn}')
plt.axvline(x=xn, linestyle='-.', label=f'a={xn}')

颜色循环

将颜色循环设置为默认值

1
plt.gca().set_prop_cycle(None)

中文字体

字体问题,中文经常显示不出来

为了防止修改以后失效、防止每次使用都要设置,建议(以linux为例):

1
2
3
4
5
6
7
8
9
cp /usr/lib/python3.11/site-packages/matplotlib/mpl-data/matplotlibrc ~/.config/matplotlib/

# ~/.config/matplotlib/matplotlibrc 最后添加

font.serif : FangSong
font.family: serif
# 负号不显示
axes.unicode_minus: False
axes.formatter.use_mathtext : False

在使用 SciencePlots 时。

即使

1
2
3
import scienceplots

plt.style.use(['science', "no-latex", "cjk-sc-font"])

注意,有些版本,cjk-sc-font 必须在最后

还是有问题,因为 scienceplots/styles/languages/cjk-sc-font.mplstyle 有问题

1
2
3
4
5
6
7
8
# scienceplots/styles/languages/cjk-sc-font.mplstyle 修改为


font.serif : FangSong
font.family: serif
# 负号不显示
axes.unicode_minus: False
axes.formatter.use_mathtext : False

FangSong 修改为你的字体,可以这样查看(两个引号之间的名字)

1
fc-list :lang=zh

测试

1
2
3
4
5
6
7
8
9
import scienceplots
from matplotlib import pyplot as plt

plt.style.use(['science', "no-latex", "cjk-sc-font"])

plt.plot([-2,-1,2,4,6,7])
plt.title("测试")
plt.xlabel(r"$\alpha$Aa")
plt.show()

逐帧播放

1
2
3
4
5
6
7
8
9
10
plt.figure()
for i in range(120):
plt.clf()
plt.title(f"{i}")
R = np.real(A[:, i]) + np.imag(A[:, i])

plt.plot((np.dot(R, A) * np.dot(R, A_))[:120], ".")
plt.pause(1)

plt.show()

高度图

三维矩阵,给一个为二维矩阵,每个格点作为颜色,画图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def plot_height_map_2d(matrix):
"""二维高度图

Args:
matrix (_type_): _description_
"""
# 将二维矩阵转换为NumPy数组
data = np.array(matrix)

# 绘制二维图 viridis 可以改,或者画图以后设置里可以看其他的
plt.imshow(data, cmap='viridis', interpolation='nearest', origin='upper')

# 添加色谱
plt.colorbar()

# 设置坐标轴标签
plt.xlabel('Column')
plt.ylabel('Row')

# 显示图形
plt.show()

三维图,给一个为二维矩阵,每个格点作为这里的高度,画图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def plot_height_map(matrix):
"""3d高度图

Args:
matrix (_type_): _description_
"""
data = np.array(matrix)

# 获取矩阵的行数和列数
rows, cols = data.shape

# 创建行和列的坐标
x = np.arange(0, cols, 1)
y = np.arange(0, rows, 1)

# 创建网格
X, Y = np.meshgrid(x, y)

# 绘制高度图
fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')
ax.set_title(f"{np.max(matrix)}")
ax.plot_surface(X, Y, data, cmap='turbo')

# 显示图形
plt.show()

多线程

1
2
3
4
5
6
7
8
from multiprocessing import Pool

def test(s):
print(s)

qv = np.linspace(134, 140, 7, dtype="int")
with Pool(4) as p:
p.map(test, qvs)

本文作者:yuhldr
本文地址https://yuhldr.github.io/posts/b4a9e8d8.html
版权声明:转载请注明出处!