Matplotlib imshow/matshow display values on plot

后端 未结 3 595
-上瘾入骨i
-上瘾入骨i 2020-12-05 03:31

I am trying to create a 10x10 grid using either imshow or matshow in Matplotlib. The function below takes a numpy array as input, and plots the gri

3条回答
  •  情书的邮戳
    2020-12-05 04:00

    Some elaboration on the code of @wflynny making it into a function that takes any matrix no matter what size and plots its values.

    import numpy as np
    import matplotlib.pyplot as plt
    
    cols = np.random.randint(low=1,high=30)
    rows = np.random.randint(low=1,high=30)
    X = np.random.rand(rows,cols)
    
    def plotMat(X):
        fig, ax = plt.subplots()
        #imshow portion
        ax.imshow(X, interpolation='nearest')
        #text portion
        diff = 1.
        min_val = 0.
        rows = X.shape[0]
        cols = X.shape[1]
        col_array = np.arange(min_val, cols, diff)
        row_array = np.arange(min_val, rows, diff)
        x, y = np.meshgrid(col_array, row_array)
        for col_val, row_val in zip(x.flatten(), y.flatten()):
            c = '+' if X[row_val.astype(int),col_val.astype(int)] < 0.5 else '-' 
            ax.text(col_val, row_val, c, va='center', ha='center')
        #set tick marks for grid
        ax.set_xticks(np.arange(min_val-diff/2, cols-diff/2))
        ax.set_yticks(np.arange(min_val-diff/2, rows-diff/2))
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_xlim(min_val-diff/2, cols-diff/2)
        ax.set_ylim(min_val-diff/2, rows-diff/2)
        ax.grid()
        plt.show()
    
    plotMat(X)
    

提交回复
热议问题