我想在Python中复制这样的东西。有人知道这是否可行?
我将有一个2D数组作为输入和行和列标签的文本列表。
应在每个单元格中绘制2D数组值,如下所示。
答案 0 :(得分:2)
由于没有人回答你,这是一个很好的起点:
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
z = np.random.rand(10, 10) # generate random data
nx, ny = z.shape
indx, indy = np.arange(nx), np.arange(ny)
x, y = np.meshgrid(indx, indy)
fig, ax = plt.subplots()
ax.imshow(z.T, interpolation="nearest", cmap=cm.YlGn) # plot grid values
for xval, yval in zip(x.flatten(), y.flatten()):
zval = z[xval, yval]
t = "%.1f%%"%(zval * 100,) # format value with 1 decimal point
c = 'w' if zval > 0.75 else 'k' # if dark-green, change text color to white
ax.text(xval, yval, t, color=c, va='center', ha='center')
xlabels = 'abcdefghij'
ylabels = '0123456789'
ax.set_xticks(indx+0.5) # offset x/y ticks so gridlines run on border of boxes
ax.set_yticks(indy+0.5)
ax.grid(ls='-', lw=2)
# the tick labels, if you want them centered need to be adjusted in
# this special way.
for a, ind, labels in zip((ax.xaxis, ax.yaxis), (indx, indy),
(xlabels, ylabels)):
a.set_major_formatter(ticker.NullFormatter())
a.set_minor_locator(ticker.FixedLocator(ind))
a.set_minor_formatter(ticker.FixedFormatter(labels))
ax.xaxis.tick_top()
plt.show()
答案 1 :(得分:1)
感谢@Bill,这是答案,从他的链接中轻轻修改
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7,7))
min_val, max_val, diff = 0., 10., 1.
#imshow portion
N_points = (max_val - min_val) / diff
random.seed(42)
imshow_data = np.random.rand(N_points, N_points)
ax.imshow(imshow_data, interpolation='nearest', cmap="GnBu" )
#text portion
ind_array = np.arange(min_val, max_val, diff)
x, y = np.meshgrid(ind_array, ind_array)
# Write the text to correct positions
for x_val, y_val in zip(x.flatten(), y.flatten()):
c = "{0:.2}".format(imshow_data[y_val, x_val])
ax.text(x_val, y_val, c, va='center', ha='center')
#set tick marks for grid
ax.set_xticks(np.arange(min_val-diff/2, max_val-diff/2))
ax.set_yticks(np.arange(min_val-diff/2, max_val-diff/2))
ax.set_xticks(np.arange(max_val))
ax.set_yticks(np.arange(max_val))
ax.set_xlim(min_val-diff/2, max_val-diff/2)
ax.set_ylim(min_val-diff/2, max_val-diff/2)
ax.grid()
plt.show()
这给出了: