我正在尝试生成稀疏数组的二维图,imshow()
并使用plt.text()
文本框将其覆盖。我想出了一个额外的选项,使用plt.scatter()
. 在第二种情况下,彩色图块和文本框太小,无法缩放。在第一种情况下,由imshow()
和文本框生成的彩色图块的大小具有不连贯的大小,并且只有在使用对话框窗口的缩放功能时,绘图才看起来很好。下面的代码说明了这一点。
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
#https://matplotlib.org/gallery/images_contours_and_fields/image_annotated_heatmap.html
P=[1, 4, 11, 18, 20, 39, 40, 41, 41, 71, 71, 71, 71, 71, 71, 72, 72, 72, 72, 72, 72, 73, 73, 73, 74, 74, 74, 74, 74, 74, 75, 75, 75, 71]
N=[2, 3, 11, 19, 25, 49, 48, 50, 54, 101, 102, 103, 103, 106, 106, 100, 103, 106, 106, 107, 109, 105, 106, 109, 104, 107, 109, 110, 111, 112, 108, 109, 109, 101]
B=np.random.rand(34)
# crate the array to use with imshow()
A=np.zeros((max(N)+1,max(N)+1))
for i,j,k in zip(N,P,B):
A[i,j]=k
def plot_map(N,P,A):
fig, ax = plt.subplots()
plt.imshow(A,norm=colors.LogNorm(),cmap='jet',origin='lower')
plt.colorbar()
for n,p in zip(N,P):
ax.text(p,n, "\n%s\n%s\n%5.1E"%(p,n,A[n,p]),
ha="center", va="center",
bbox=dict(fc="none",boxstyle = "square"))
plt.tight_layout()
plt.show()
# call the plot function
plot_map(N,P,A)
# attempt tow using plt.scatter()
plt.scatter(N,P,c=B,marker='s',s=70,norm=colors.LogNorm(),cmap='jet')
for n,p in zip(N,P):
plt.text(n,p, "\n%s\n%s"%(p,n), size=3,
va="center", ha="center", multialignment="left",
bbox=dict(fc="none",boxstyle = "square"))
plt.colorbar()
plt.show()
理想情况下,我想制作这样的东西
我的绘图程序生成的东西看起来不太好,彩色瓷砖和注释框都是不连续的。
因此,我将感谢您的帮助。