回应阿斯穆斯:
这是一个非常好的开始。我试图获取您的代码并对其进行修改,但不幸的是出了点问题。有些单元格不是我告诉他们的颜色。
我也很好奇是否可以制作这个的 3 维版本。这将有不同颜色的 3-d 单元格,每个单元格代表不同的 3 字母排列,其中如果两个单元格包含完全相同的 3 个字母,则它们具有相同的颜色。
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
### create a dictionary with:
# dictionary keys: will be used as color index
# "name": "AB" <-- the text value
# "color": "#ff0000" <-- a hex color value to represent each square
# "coordinate": [1,0] <-- coordinates as x in (0,1,2)
# and y-index (0,1) : where to plot this entry
white = "#ffffff"
grey = "#cecece"
red = "#ff0000"
green = "#00ff00"
purple = "#ccbbee"
pink = "#ffaabb"
dataDict={
1:{"name":"A",
"color":white,
"coordinate": [0, 1]},
2:{"name":"B",
"color":white,
"coordinate": [0, 2]},
3:{"name":"C",
"color":white,
"coordinate": [0, 3]},
4:{"name":"A",
"color":white,
"coordinate": [1, 0]},
5:{"name":"B",
"color":white,
"coordinate": [2, 0]},
6:{"name":"C",
"color":white,
"coordinate": [3, 0]},
7:{"name":"AA",
"color":grey,
"coordinate":[1,1]},
8:{"name":"AB",
"color":green,
"coordinate":[2,1]},
9:{"name":"AC",
"color":pink,
"coordinate":[3,1]},
10:{"name":"BA",
"color":green,
"coordinate":[1,2]},
11:{"name":"BB",
"color":grey,
"coordinate":[2,2]},
12:{"name":"BC",
"color":purple,
"coordinate":[3,2]},
13:{"name":"CA",
"color":pink,
"coordinate":[1,3]},
14:{"name":"CB",
"color":purple,
"coordinate":[2,3]},
15:{"name":"CC",
"color":grey,
"coordinate":[3,3]}
}
### define the size of your array in x- and y-direction
x_size=4
y_size=4
### create an empty image array of proper dimensions
img_array = np.zeros((y_size,x_size))
### iterate over the dictionary:
# - looking up the color index (0-5)
# - and store it in the img_array
for i,v in dataDict.items():
[xi,yi]=v["coordinate"]
img_array[yi,xi] = i
### create a colormap which
# maps the dictionary keys (0-5) to the respective color value
cmap = ListedColormap([v["color"] for i,v in dataDict.items()])
### create a figure and subplot
fig,ax=plt.subplots(1,1)
### tell the subplot to show the image "img_array" using the colormap "cmap"
ax.imshow(img_array,cmap=cmap,zorder=1,origin="upper")
#### iterate over the dictionary, get the coordiantes and names, and place text
for i,v in dataDict.items():
print(i,v["coordinate"][0],v["coordinate"][1])
ax.text(v["coordinate"][0],v["coordinate"][1],v["name"],zorder=2,)
### shwo the plot
plt.show()