Skip to main content
 首页 » 编程设计

python之使用 matplotlib 将 2 个表对象绘制为子图

2024年09月07日8落叶

我在列表中有 2 个 matplotlib 表对象,我试图将每个表绘制为子图。到目前为止,Stack Exchange 上的所有答案似乎都与绘制子图或绘制单个表格有关。

下面的代码只生成我要绘制的第二个表,而不是第一个。

import matplotlib.pyplot as plt 
import numpy as np 
 
list_of_tables = [] 
a = np.empty((16,16)) 
 
for i in range(0, 2): 
    a.fill(i) 
    the_table = plt.table( 
        cellText=a, 
        loc='center', 
    ) 
    list_of_tables.append(the_table) 
 
plt.show() 

所以我听从了各种教程的建议并提出了以下建议:

import matplotlib.pyplot as plt 
import numpy as np 
 
list_of_tables = [] 
a = np.empty((16,16)) 
 
for i in range(0, 2): 
    a.fill(i) 
    the_table = plt.table( 
        cellText=a, 
        loc='center', 
    ) 
    list_of_tables.append(the_table) 
 
fig = plt.figure() 
ax1 = fig.add_subplot(list_of_tables[0]) 
ax2 = fig.add_subplot(list_of_tables[1]) 
ax1.plot(list(of_tables[0]) 
ax2.plot(list_of_tables[1]) 
 
plt.show() 

但是当这段代码调用add_subplot方法时,会产生如下错误。

TypeError: int() argument must be a string, a bytes-like object or a number, not 'Table'.

如何将每个表绘制为子图?

请您参考如下方法:

您将表实例保存在一个列表中,然后尝试使用 plt.plot 绘制它们,它需要一个数字列表。

一种可能性是创建子图,然后使用面向对象的 API 将表格绘制到特定轴:

import matplotlib.pyplot as plt 
import numpy as np 
 
fig, axes = plt.subplots(1, 2) 
 
a = np.empty((16, 16)) 
 
for i in range(0, 2): 
    a.fill(i) 
    the_table = axes[i].table( 
        cellText=a, 
        loc='center', 
    ) 
    axes[i].axis("off")   
 
plt.show() 

给出: