Search code examples
pythonmatplotlibpixelreshape

2D pixel plot with matplotlib


I have a question regarding 2D pixel plots similar to this: Make a 2D pixel plot with matplotlib

The provided answer works, but I would like to change the direction of y axis. My code looks like this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

x = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3])
y = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3])
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
grid = a.reshape(3, 3)

plt.imshow(grid, extent=(x.min(), x.max(), y.min(), y.max()), interpolation='nearest', cmap=cm.jet, aspect="auto")

The problem is that after the reshape, the grid looks like this:

>grid
   array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]])

For the plot I want to make, I would need a grid like this:

>grid
 array([[3, 6, 9],
        [2, 5, 8],
        [1, 4, 7]])

I have looked into options of reshape but could not find anything that helped. Any advice on how I could change my grid?


Solution

  • Just use

    grid.T[::-1]
    

    or

    a.reshape(3,3).T[::-1]
    

    This transposes the matrix and reverses the ordering of the rows which gives you the correct shape.

    Reversing the order of the rows can also done in imshow using origin

    plt.imshow(grid.T,origin='lower', ...)