import numpy as np
import matplotlib.pyplot as plt
# 创建一个19x19的数组,并将所有值初始化为0
image_size = 17
image = np.zeros((image_size, image_size))
# 设置中心点的值为10
center_x, center_y = image_size // 2, image_size // 2
image[center_x, center_y] = 9
# 逐渐减小每个格点的值
for r in range(1, image_size // 2 + 1):
for i in range(center_x - r, center_x + r + 1):
for j in range(center_y - r, center_y + r + 1):
if 0 <= i < image_size and 0 <= j < image_size:
distance = np.sqrt((i - center_x) ** 2 + (j - center_y) ** 2)
image[i, j] = 10 - distance
# 绘制图像
plt.imshow(image, cmap='rainbow', interpolation='nearest')
# 添加网格线
for i in range(image_size + 1):
plt.axhline(y=i-0.5, color='lightgrey', lw=0.2)
plt.axvline(x=i-0.5, color='lightgrey', lw=0.2)
# 禁用x轴和y轴上的刻度值
plt.xticks([])
plt.yticks([])
# plt.colorbar()
# 添加图例并设置字体为新罗马体
# legend = plt.legend(['distance'], loc='upper right', prop={'family': 'serif'})
# 添加颜色条标签为"distance"并设置字体为新罗马体
cbar = plt.colorbar()
cbar.set_label('distance', family='serif')
# 自定义颜色条的刻度和标签
cbar.set_ticks([0,2,4,6,8,10])
cbar.set_ticklabels(['0','2','4', '6','8',' ' ])
# 使用annotate方法将标签放在颜色条上方,设置为两行
cbar.ax.annotate('center point', xy=(0.8, 9.5), xytext=(0, 20), textcoords="offset points", ha='center', va='center')
plt.show()
结果