display matrix values and colormap

后端 未结 2 1737
醉酒成梦
醉酒成梦 2021-02-04 07:31

I need to display values of my matrix using matshow. However, with the code I have now I just get two matrices - one with values and other colored. How do I impose them? Thanks

相关标签:
2条回答
  • 2021-02-04 08:13

    You need to use ax.matshow not plt.matshow to make sure they both appear on the same axes.

    If you do that, you also don't need to set the axes limits or ticks.

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    min_val, max_val = 0, 15
    
    intersection_matrix = np.random.randint(0, 10, size=(max_val, max_val))
    
    ax.matshow(intersection_matrix, cmap=plt.cm.Blues)
    
    for i in xrange(15):
        for j in xrange(15):
            c = intersection_matrix[j,i]
            ax.text(i, j, str(c), va='center', ha='center')
    

    Here I have created some random data as I don't have your matrix. Note that I had to change the ordering of the index for the text label to [j,i] rather than [i][j] to align the labels correctly.

    0 讨论(0)
  • 2021-02-04 08:18

    In Jupyter notebooks this is also possible with DataFrames and Seaborn:

    import numpy as np
    import seaborn as sns
    import pandas as pd
    
    min_val, max_val = 0, 15
    intersection_matrix = np.random.randint(0, 10, size=(max_val, max_val))
    cm = sns.light_palette("blue", as_cmap=True)
    x=pd.DataFrame(intersection_matrix)
    x=x.style.background_gradient(cmap=cm)
    display(x)
    

    0 讨论(0)
提交回复
热议问题