Skip to main content
 首页 » 编程设计

python之在 matplotlib imshow 函数中更改像素形状

2025年05月04日13小虾米

我正在尝试从 matplotlib 中的一篇论文中复制一个图形,如下所示。基本上,每个单元格中都有一个百分比,百分比越高,单元格的背景越暗:

下面的代码产生类似的东西,但每个单元格都是一个正方形像素,我希望它们是更平坦的矩形而不是正方形,如上图所示。我怎样才能用 matplotlib 实现这个目标?

import numpy as np 
import matplotlib.pyplot as plt 
import itertools 
 
table = np.random.uniform(low=0.0, high=1.0, size=(10,5)) 
 
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] 
 
plt.figure() 
plt.imshow(table, interpolation='nearest', cmap=plt.cm.Greys, vmin=0, vmax=1) 
plt.yticks(np.arange(10), class_names) 
 
for i,j in itertools.product(range(table.shape[0]), range(table.shape[1])): 
    plt.text(j, i, format(table[i,j], '.2f'), 
             horizontalalignment="center", 
             color="white" if table[i,j] > 0.5 else "black") 
 
plt.show() 

下面是上面这段代码产生的结果:

我怀疑更改 aspect 和 imshow 的 extent 可能对我有帮助。我不完全理解这是如何工作的,但这是我尝试过的:

plt.imshow(table, interpolation='nearest', cmap=plt.cm.Greys, vmin=0, vmax=1, aspect='equal', extent=[0,14,10,0 ])

这会产生以下内容:

我意识到我还需要添加单元格之间的边框,删除刻度线,并将值更改为百分比而不是小数,我相信我自己能够做到这一点,但是如果你也想帮我解决这个问题,请随意!

请您参考如下方法:

在 imshow 调用中使用 aspect="auto" 时,您将获得非方形像素:

import numpy as np 
import matplotlib.pyplot as plt 
import itertools 
 
table = np.random.uniform(low=0.0, high=1.0, size=(10,5)) 
 
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] 
 
plt.figure() 
plt.imshow(table, interpolation='nearest', cmap=plt.cm.Greys, vmin=0, vmax=1, aspect="auto") 
plt.yticks(np.arange(10), class_names) 
 
for i,j in itertools.product(range(table.shape[0]), range(table.shape[1])): 
    plt.text(j, i, format(table[i,j], '.2f'), 
             ha="center", va="center", 
             color="white" if table[i,j] > 0.5 else "black") 
 
plt.show()