Matplotlib 3.0 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

The following code block defines the function and makes a call to the function to plot the Hinton diagram:

  1. Read the weight matrix data from an Excel file:
matrix = np.asarray((pd.read_excel('weight_matrix.xlsx')))
  1. Instantiate the figure and axes:
fig, ax = plt.subplots()
  1. Set up the parameters for the axes:
ax.patch.set_facecolor('gray')
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
  1. Plot the Hinton diagram:
max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))
for (x, y), w in np.ndenumerate(matrix):
color = 'white' if w > 0 else 'black'
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color)
ax.add_patch(rect)
ax.autoscale_view()
  1. Display it on the screen:
plt.show()