python3 绘制盖尔圆
程序员文章站
2022-05-22 15:49:50
...
import numpy as np
import matplotlib.pyplot as plt
row_num = int(input("input nums of row:"))
# 用0初始化矩阵
mat = [[0] * row_num] * row_num
# 字符串分割成数字并转为复数类型
for i in range(row_num):
mat[i] = input().split()
mat[i] = [complex(j) for j in mat[i]]
mat = np.array(mat)
print(mat)
# 画圆采样
sample = np.linspace(-np.pi, np.pi, 100)
# 保持x,y轴刻度比例相同
plt.axis('equal')
for i in range(row_num):
# 盖尔圆半径
r = sum(abs(mat[i][:])) - abs(mat[i][i])
# 盖尔圆圆心
point_x = mat[i][i].real
point_y = mat[i][i].imag
# 绘制圆心
plt.plot(point_x, point_y, '.b')
# 绘制圆(填充)
plt.fill(r * np.sin(sample) + point_x,
r * np.cos(sample) + point_y,
'b',
alpha=0.2)
# 标注
plt.text(point_x,
point_y,
"G" + str(i + 1),
fontdict={
'size': '12',
'color': 'k'
})
ax = plt.gca()
# 去掉默认边缘边框
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 设置x与y轴的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# 指定x与y轴刻度数字位置
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.show()
输入test:
输出:
画圆部分,matplotlib 中没有直接根据圆心和半径画圆的方法,所以用采样(微分)的方法来绘制
import numpy as np
import matplotlib.pyplot as plt
sample = np.linspace(-np.pi, np.pi, 100)
# 半径为 r,圆心为(point_x, point_y)
plt.fill(r * np.sin(sample) + point_x, r * np.cos(sample) + point_y)
对 list 中元素类型进行统一转换,可一句搞定
l = ["12", "2.333", 23]
l1 = [float(i) for i in l]
下一篇: 武汉加油——传染病模型概念与模拟