我大量借用了this post的表格結構。
這裏的區別在於構造數組數據。通過用零初始化數組,對於每個座標(i,j),將該數組元素遞增1以表示增加後的頻率。
zip(*coords)
將把所有的i
組合成一個元組,並將所有的j
組合在另一個元組中。通過在每個中找到最大值,我們知道數組的大小。注意,這必須從x
和y
加大1以使其佔0,即從0到x是x + 1行。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.table import Table
def table_plot(data):
fig, ax = plt.subplots()
ax.set_axis_off()
tb = Table(ax, bbox=[0,0,1,1])
nrows, ncols = data.shape
width, height = 1.0/ncols, 1.0/nrows
for (i, j), val in np.ndenumerate(data):
tb.add_cell(i, j, width, height, text=str(val) if val else '', loc='center')
for i in range(data.shape[0]):
tb.add_cell(i, -1, width, height, text=str(i), loc='right',
edgecolor='none', facecolor='none')
for i in range(data.shape[1]):
tb.add_cell(-1, i, width, height/2, text=str(i), loc='center',
edgecolor='none', facecolor='none')
tb.set_fontsize(16)
ax.add_table(tb)
return fig
coords = ((1,2), (2,5), (1,2), (5, 5), (4, 5))
# get maximum value for both x and y to allocate the array
x, y = map(max, zip(*coords))
data = np.zeros((x+1, y+1), dtype=int)
for i, j in coords:
data[i,j] += 1
table_plot(data)
plt.show()
輸出:
![enter image description here](https://i.stack.imgur.com/k4ABS.png)
您可以發佈您的數據樣本,什麼解決方案應該是什麼樣子 – Chris
可能的複製[自定義matplotlib陰謀:國際象棋棋盤如表彩色細胞( HTTP://計算器。com/questions/10194482/custom-matplotlib-plot-chess-board-like-table-with-colored-cells) – Reti43
Reti43確實看起來很相似,但輸入數據是一步之遙,也是我的一個難題。 – burkesquires