Search code examples
python-2.7matplotlibaxescolormap

Matplotlib: Increase ax.matshow width/height, and set color map (cmap) to transparent


I have a matrix built of random values and I plotted it with ax.matplot, where the value of each matrix cell is plotted in the center of the matrix cell, and I need to increase the size of the plot (specially the width) and also set the color map (cmap) to "transparent", where the cells of the matrix plot will be white and the matrix value in the center of the cell with be black.

The code:

import numpy as np
import matplotlib.pyplot as plt

low_dim = 0
high_dim = 20

matrix = np.random.randint(low_dim, high_dim, (high_dim,high_dim))
print (matrix)
fig, ax = plt.subplots()

ax.matshow(matriz, cmap=None,interpolation='nearest')

for i in xrange(20):
    for j in xrange(20):
        number = matrix[j,i]
        ax.text(i, j, str(number), va='center', ha='center')


plt.show()

EDIT

That's matrix in the code (https://i.sstatic.net/e3mGO.png (matrix), a matrix generated with the command matrix = np.random.randint(low_dim, high_dim, (high_dim,high_dim)), the picture is from the console.

I've tried changing the figsize in fig,ax = plt.subplot(),but it doesn't change anything. And I've also set cmap = none but nothing happened.

Another problem is that, in the first picture, the numbers in the index of x and y axes are varying from 0 to 15 and stepping 5, like 0, 5, 10, 15 (I've marked it in red). But in the second picture (also marked in red), the values are from 0 to 19,with no step. If possible, I need to arrive to the second picture's result, the indexes varying from 0 to 19 with no step.

Picture 1: What I'm getting: https://i.sstatic.net/mlExQ.png

Picture 2: What I need to get: https://i.sstatic.net/T3CC4.png


Solution

  • matshow takes arguments for origin and alpha. The rest is just settings ticks and labels.

    ax.matshow(matrix, origin='lower', alpha=0, cmap=None, interpolation='nearest')
    
    tick_labels = range(high_dim)
    ax.set_xticks([], minor=False)
    ax.set_xticks(np.arange(-.5, 20, 1), minor=True)
    ax.set_yticks([], minor=False)
    ax.set_yticks(np.arange(-.5, 20, 1), minor=True)
    ax.set_xticklabels([], minor=False)
    ax.set_xticklabels(tick_labels, minor=True)
    ax.set_yticklabels([], minor=False)
    ax.set_yticklabels(tick_labels, minor=True)
    ax.xaxis.set_ticks_position('bottom')
    ax.grid(which='minor', color='grey', linestyle='-', linewidth=1)