Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use matplotlib's imshow and contour plot on the same numpy array?

With the following code I am producing an obstacle on a 2D Cartesian grid (used later as input for some simulations) by defining the area where the obstacle is located as 1 and 0 everywhere else.

I wanted to plot it using a contour plot, but had some troubles producing a binary filled contour plot (side question: how to achieve that?) and so decided to plot the array as an image.

Here is the code:

import numpy as np, matplotlib.pyplot as plt

# create spatial coordinates
N_x, N_y = 161, 161
x = np.linspace( .0, .80, N_x )
y = np.linspace( .0, .80, N_y )

# define obstacle
obst_diameter = .3
obst_center   = (.4,.2)

# 2D array defining obstacle structure: 1=obstacle, 0=nothing
metal = np.zeros( (N_x, N_y), dtype=int )

for ii in range(N_x):
    for jj in range(N_y):
        if (     x[ii] >= (obst_center[0]-obst_diameter/2)
             and x[ii] <= (obst_center[0]+obst_diameter/2)
             and y[jj] >= (obst_center[1]-obst_diameter/2)
             and y[jj] <= (obst_center[1]+obst_diameter/2)
           ):
            metal[jj,ii] = 1.

# do the plotting (contour and imshow)
xx, yy = np.meshgrid( x, y )
fig = plt.figure( figsize=(20,10) )

ax1 = fig.add_subplot( 1,2,1, aspect='equal' )
cont_obst = ax1.contour( xx, yy, metal, colors='k', levels=[0,1] )
ax1.plot( obst_center[0], obst_center[1], marker='*', markersize=30, color='yellow' )
ax1.set_xlabel( 'x in m' )
ax1.set_ylabel( 'y in m' )

ax2 = fig.add_subplot( 1,2, 2, aspect='equal' )
ax2.imshow( metal, cmap='Greys', interpolation='none',
        extent=[np.min(x), np.max(x), np.min(y), np.max(y)] )
ax2.plot( obst_center[0], obst_center[1], marker='*', markersize=30, color='yellow' )
ax2.set_xlabel( 'x in m' )
ax2.set_ylabel( 'y in m' )

plt.savefig( 'another_plot.png', bbox_inches='tight' )

The resulting image looks as follows, with the contour plot on the left and the imshow plot on the right (the center of the obstacle is marked with a yellow star).

Contour and imshow

Obviously, the two plots are different. What is the reason for this, i.e. what am I missing here?

like image 980
Alf Avatar asked Jul 30 '26 11:07

Alf


1 Answers

The origin for matplotlib's imshow function is the top left corner. If you change the relevant line to:

ax2.imshow( metal, cmap='Greys', interpolation='none',
        extent=[np.min(x), np.max(x), np.min(y), np.max(y)], origin='lower')

It will fix this issue.

like image 82
Robbie Avatar answered Aug 01 '26 01:08

Robbie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!