Home > Blockchain >  centering a contour plot over a 2D colour grid plot using matplotlib
centering a contour plot over a 2D colour grid plot using matplotlib

Time:01-13

I have two 10x10 sized arrays. One of them I use to display the array's values as a 2D color grid of squares. The other I use to draw a contour plot over this 2D grid. This way I can show relations between the values in the two arrays.

Some example data for my problem:

import matplotlib.pyplot as plt
import numpy as np

# make some random data
squares = np.random.random((10,10))
contour = np.random.random((10,10))

# plot squares
plt.pcolor(squares, cmap='bone')
plt.colorbar()
# plot contour
plt.contour(contour, levels=10)
plt.colorbar()
plt.show()

Running this code plots them over one another as needed, however the contour plot is shifted to the lower left corner and does not fill out the full figure with the squares. How can I center this contour plot without having to increase the size of my contour plot array to (11,11) but rather shifting it half a square up and to the right?

Any help is appreciated

CodePudding user response:

The pcolor plot colors cells of 1x1, where the borders are formed by the 11 values 0, 1, 2, ..., 10. The contour plot, when no explicit X and Y are given, supposes "heights" given at point positions, so at X and Y values for the 10 coordinate values going 0, 1, 2, ..., 9.

To align both, you could tell plt.contour that the values are meant for the centers of the cells, so with coordinate values 0.5, 1.5, 2.5, ..., 9.5 (written with numpy e.g. as np.arange(10) 0.5.

import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage.filters import gaussian_filter

# make some random data
heights = gaussian_filter(np.random.randn(10, 10), 2)

# plot squares
plt.pcolor(heights, cmap='bone')
plt.colorbar()
# plot contour
plt.contour(np.arange(10)   0.5, np.arange(10)   0.5, heights, levels=10, cmap='Reds')
plt.colorbar()
plt.show()

aligning plt.pcolor and plt.contour

  • Related