You are reading documentation for the unreleased version of Matplotlib. Try searching for the released version of this page instead?
Version 3.1.0.post919+g4ce649c38
Fork me on GitHub

Related Topics

Hinton diagramsΒΆ

Hinton diagrams are useful for visualizing the values of a 2D array (e.g. a weight matrix): Positive and negative values are represented by white and black squares, respectively, and the size of each square represents the magnitude of each value.

Initial idea from David Warde-Farley on the SciPy Cookbook

import numpy as np
import matplotlib.pyplot as plt

def hinton(matrix, max_weight=None, ax=None):
    """Draw Hinton diagram for visualizing a weight matrix."""
    ax = ax if ax is not None else plt.gca()

    if not max_weight:
        max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

    ax.set_aspect('equal', 'box')

    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)


if __name__ == '__main__':
    # Fixing random state for reproducibility

    hinton(np.random.rand(20, 20) - 0.5)

Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery